我在将 javascript 变量发布到 php 文件时遇到问题。请有人告诉我发生了什么事吗?
// Get Cookies
var getCookies = document.cookie;
cookiearray = getCookies.split(';');
SelectedIds = cookiearray[0];
//take key value pair
name = cookiearray[0].split('=')[0];
value = cookiearray[0].split('=')[1]; // The variable(values) i want to pass
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
hr.open("POST", url, true);
var url = "page.php";
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("Comp").innerHTML = return_data;
}
}
hr.send(value); // Request - Send this variable to PHP
document.getElementById("Comp").innerHTML = "loading...";
PHP
$test = $_POST['value'];
print_r($test); // NULL
谢谢
最佳答案
代替
print_r($test);
使用 echo
echo $test;
因为 $test
不是数组,而是字符串值。 print_r
用于打印数组。这就是为什么 被赋予 null 值。
而您在 ajax 中的发送函数应该是这样的:
hr.send("value="+value);
在send函数中,传递的参数必须是这样的字符串:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
关于php - 使用 xmlhttprequest 将 javascript 变量传递给 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20494437/