我想使用 native javascript 将 json 发送到 php 文件。为什么 get-translation.php 中的 $_POST 是空的?
var xmlhttp;
json_data = JSON.stringify(a_data);
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","get-translation.php",true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(json_data); // json_data is simple json
最佳答案
$_POST 仅适用于默认内容类型 application/x-www-form-urlencoded
。
对于任何其他类型的数据(包括 JSON),您需要解析原始输入流。
file_get_contents('php://input')
将返回原始请求正文。由于这是 JSON,因此需要使用 json_decode 将 json 数据解析为关联数组。
$jsonData = json_decode(file_get_contents('php://input'));
关于php - 使用原生 javascript 发送 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17790447/