gpt4 book ai didi

javascript - PHP 脚本未收到发布的 JSON

转载 作者:行者123 更新时间:2023-11-29 19:32:13 24 4
gpt4 key购买 nike

我在使用以下 JavaScript 时遇到问题,其中数据是 JavaScript 对象:

var ajax_send = function(data) {
var httpRequest;

makeRequest('/prototype/test.php', data);

function makeRequest(url, data) {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}

if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}

httpRequest.onreadystatechange = alertContents;
httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/json');
httpRequest.send(JSON.stringify(data));
}

function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
};

PHP 是:

$data = $_POST['data'];
$obj = json_decode($data);
echo $obj;

在开发工具中,请求有效负载看起来 没问题,但它似乎不是 PHP 正在寻找的内容。没有任何内容到达 PHP 脚本,响应为空。

我做错了什么?

最佳答案

当您发送带有 Content-Type: application/json 的 POST 请求时,PHP 的工作方式略有不同。

您将需要像这样访问它:

$postData = json_decode(file_get_contents('php://input'));

而不是通常的 $_POST

如果您想将其作为将填充到 $_POST 的常规表单发送,您需要像这样设置标题:

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

然后像这样填充您的字段:

key=value&key2=value2&key3=value3

等等

关于javascript - PHP 脚本未收到发布的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26866600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com