为什么这个简单的JavaScript + Ajax + php代码不起作用?

时间:2017-04-12 08:16:47

标签: javascript php ajax

我是ajax的新手,我正在尝试将html页面数据发送到php而不重新加载当前页面。当我点击提交按钮时,它只是闪烁“处理......”

html文件

<!DOCTYPE html>
<head>
<script type="text/javascript">
function ajax_post(){
    var hr = new XMLHttpRequest();
    var url = "simple.php";
    var fn = document.getElementById("first_name").value;
    var ln = document.getElementById("last_name").value;
    var vars = "firstname="+fn+"&lastname="+ln;
    hr.open("POST", url, true);
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            document.getElementById("status").innerHTML = return_data;
        }
    }
    hr.send(vars);
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
First Name: <input id="first_name" name="first_name" type="text">  <br><br>
Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>`

Php档案

<?php 
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>

修改1

我在onreadystatechange中添加了警告消息。它分别显示三条警报消息2,3,4。

alert(hr.readyState);

1 个答案:

答案 0 :(得分:0)

我可以看到很多事情:

  1. </script>关闭脚本中没有任何开头标记的脚本。
  2. 变量vars没有创建查询字符串,因为它缺少?
  3. 因此,完整的更改将是:

    <head>
        <script type="text/javascript">
        function ajax_post(){
            var hr = new XMLHttpRequest();
            var url = "simple.php";
            var fn = document.getElementById("first_name").value;
            var ln = document.getElementById("last_name").value;
            var vars = "?firstname="+fn+"&lastname="+ln;
            //----------^---put this at start.
            hr.open("POST", url, true);
            hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            hr.onreadystatechange = function() {
                if(hr.readyState == 4 && hr.status == 200) {
                    var return_data = hr.responseText;
                    document.getElementById("status").innerHTML = return_data;
                }
            }
            hr.send(vars);
            document.getElementById("status").innerHTML = "processing...";
        }
        </script>
    </head>
    

    或者您可以将其发送为:

    hr.send({ firstname:fn, lastname:ln });