php - 使用 xmlhttprequest 将 javascript 变量传递给 PHP

标签 php ajax xmlhttprequest

我在将 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"

More tutorial is here.

关于php - 使用 xmlhttprequest 将 javascript 变量传递给 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20494437/

相关文章:

php - 使用ajax更新数据库-处理错误

php - 处理连续的 Ajax 请求 - JQUERY

javascript - 从浏览器发出 HTTP 请求,而不在请求 header 中发送任何 cookie

javascript - Uncaught ReferenceError : xmlhttp is not defined?

php - 如何始终在正方形中显示图像

PHP:按今天/昨天制作过滤器

PHP DOM - 将 THEAD 中的 TD 标签替换为 TH 标签

javascript - Internet Explorer (IE) 中的脚本挂起并且对空缓存不负责任(在缓存中工作正常)

javascript - jQuery.ajax() 错误与 textStatus=error

php - CodeIgniter SELECT 语句错误结果