在表单html上编程php和警告javascript


program php and alert javascript on form html

我在php中的简单程序有问题,该程序包含一个警报javascript。这是代码:

<?php
function iva(){
$country='IT';
$vatnum=$_POST['n'];
$a="Work";
$b="NotWork";
$url='http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
 $response = file_get_contents($url);
//global $a, $b;
if( $response == 'true' ){
echo $a;
}
if ($response != 'true'){
echo $b;
}
}
?>
<script>
function ivaz(){
alert("<?php iva() ?>");
}
</script> 
<form method="post">
<input name="n"  type="textarea" >
<input  onclick="ivaz();" value="Validate" type="submit"> </input> </form>

我的程序从输入文本框中获取一个值,并将该值传递给php脚本,该脚本在javascript警报中返回true或false。程序工作,但返回在输入框中传递的上一个值。有人能帮我解决吗?

谢谢大家。

不,它不是那样工作的。如果您想在不刷新页面的情况下从Javascript调用PHP函数,则需要一个XMLHttpRequest。

示例:

<?php
// your php process when called by XMLHttpRequest
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $vatnum = $_POST['n'];
    $country='IT';
    $a = "Work";
    $b = "NotWork";
    $url = 'http://isvat.appspot.com/'.$country.'/'.$vatnum.'/';
    $response = file_get_contents($url);
    //global $a, $b;
    if( $response == 'true' ){
        echo $a;
    } else {
        echo $b; 
    }
    exit;
}
?>
<form method="post" id="form1">
    <input name="n" type="text" id="n" />
    <input value="Validate" type="submit">
</form>
<script type="text/javascript">
// when the form is submitted
document.getElementById('form1').addEventListener('submit', function(e){
    e.preventDefault(); 
    var n = document.getElementById('n').value; // get the textbox value
    var xmlhttp = new XMLHttpRequest();
    var params = 'n=' + n;
    var php_url = document.URL;
    xmlhttp.open('POST', php_url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var response = xmlhttp.responseText;
            alert(response); // alert the server response
        }
    }
    xmlhttp.send(params);
});
</script>

从输入标签中删除onclick="ivaz();"

您不能在不重新加载页面的情况下运行php脚本,因为php是在服务器端生成的,javascript是在客户端运行的。