Ajax发送到变量到php undefined索引

时间:2011-12-12 19:02:02

标签: php javascript html ajax variables

我想在php页面中显示变量num

我得到的错误如下:

  

注意:未定义的索引:第4行的C:\ xampp \ htdocs \ javas.php中的num

PHP:

<?php 
$lol = $_POST['num'];
echo "$lol " ;
?>

HTML /使用Javascript:

<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "javas.php";
var num = "lol";

hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(num); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>

<input name="myBtn" type="submit" value="increment" onClick="javascript:ajax_post();">
<br /><br />
<div id="status"></div>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

您必须发送名称/值对

hr.send(“num =”+ num);

答案 1 :(得分:0)

此处的问题的一部分是您发布的参数未正确序列化。 POST的参数字符串类似于GET请求的查询字符串:

var1=foo&var2=bar

就目前而言,您只需发送一段原始数据(分配给变量num的值。