在php中显示警告框


showing alert box in php

在下面的代码中,当字段中没有输入值时,警告框将出现在另一个窗口中。但我希望警报框出现在同一窗口的HTML页面(detail.htm)。我该怎么做呢?

detail.htm:

<body>    
    <h1> Product: </h1>
    <form  action="product.php"  method="post"  >
        <input type="text" name= "product_id" size="15" />
        <input type="text" name= "price" size="10"/>
        <input type = "submit"  value = "enter" /> 
    </form>        
</body>

product.php:

if (empty($_POST["product_id"]) || empty($_POST["price"])) {
    echo "<script>alert('You must enter both values.')</script>";
} else {
    include 'product.htm';
}

我认为你应该使用客户端验证:

<script language="javascript">
    function validate() {
        if (document.forms[0].product_id.value == "") {
            window.alert("You must enter both values");
            return false;
        }
        if (document.forms[0].price.value == "") {
            window.alert("You must enter both values");
            return false;
        }
    }
</script>
然后在FORMonsubmit事件上调用validate()函数,如
<form action="product.php"  method="post" onsubmit="return validate();">

您必须在Javascript中实现客户端检查。

给你的表单一个ID,使用JavaScript(或使用jQuery等库),并做以下事情:

$('#id-of-the-form').submit(function(e) {
    var self = this;
    e.preventDefault();
    var found_empty = false;
    $('#id-of-the-form').find(':input').each(function() {
        if ($(this).val() == '') {
            found_empty = true;
        }
    });
    if (found_empty) {
        alert('Please enter all values!');
    }
    else {
        $(this).submit();
    }
});

请注意,我在这个例子中使用jQuery !

作为参考,我使用jQuery来观察表单的提交,获取表单的所有字段并检查字段是否为空。