如何使用原始AJAX将数据从客户端传递到服务器?

时间:2016-11-03 02:32:37

标签: javascript php ajax

您好我已经搜索过,但他们经常使用jquery ajax将数据从js传递给PHP(服务器端)。但对于我的项目,它有一堆纯js代码,所以我应该使用原始AJAX来传递数据。

例如,如果我想发送一个变量“Imgname”,其值= 13,并希望在php页面中回显。

这是我的尝试

<script>
    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                alert('send to server successfully');
            }
        };
        xmlhttp.open("POST", "test2.php", true);
        xmlhttp.send("Imgname=13");
    }
</script>

在test2.php中

<?php
$temp = $_POST['Imgname'];
echo $temp;   /////output should be 13
?>

但错误未定义的索引:第2行的C:\ xampp \ htdocs \ test2.php中的Imgname

2 个答案:

答案 0 :(得分:2)

您需要确保发送正确的内容类型:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

答案 1 :(得分:2)

尝试发送标题:

var http = new XMLHttpRequest();
var url = "test2.php";
var params = "Imgname=13";
http.open("POST", url, true);

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
  }
}
http.send(params);