[英]Send JSON data to PHP using XMLHttpRequest w/o jQuery
I am trying to send JSON data from a form using the XMLHttpRequest object. 我正在尝试使用XMLHttpRequest对象从表单发送JSON数据。 I can send the data using the following function.
我可以使用以下函数发送数据。 There are no errors displayed in FireBug and the JSON-data in the request is displayed well formed by FireBug.
FireBug中没有显示错误,请求中的JSON数据显示为FireBug。
However, I send the data to echo.php , what simply returns the content: 但是,我将数据发送到echo.php ,简单地返回内容:
<?php
print_r($_POST);
print_r($_GET);
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
echo file_get_contents('php://input');
?>
The POST-array is always empty, but I can see the JSON string returned by file_get_contents
. POST数组始终为空,但我可以看到
file_get_contents
返回的JSON字符串。 How does that happen? 这是怎么发生的? What am I doing wrong?
我究竟做错了什么?
output of echo.php echo.php的输出
Array
(
)
Array
(
)
Host: localhost
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: eo,de-de;q=0.8,de;q=0.6,en-us;q=0.4,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Referer: http://localhost/form.html
Content-Length: 88
Cookie: {{..to much data..}}
Pragma: no-cache
Cache-Control: no-cache
{"type":"my_type","comment":"commented"}
the sending function: 发送功能:
function submit(){
var data={};
data.type=document.form.type.value;
data.comment=document.form.comment.value;
//get right XMLHttpRequest object for current browsrer
var x=ajaxFunction();
var string = JSON.stringify(data);
x.open('POST','echo.php',true);
x.setRequestHeader('Content-type','application/json; charset=utf-8');
x.setRequestHeader("Content-length", string.length);
x.setRequestHeader("Connection", "close");
x.onreadystatechange = function(){
if (x.readyState != 4) return;
if (x.status != 200 && x.status != 304) {
alert('HTTP error ' + req.status);
return;
}
data.resp = JSON.parse(x.responseText);
if(data.resp.status=='success'){
alert('That worked!');
}else{
alert('That didn\'t work!');
}
}
x.send(string);
return false; //prevent native form submit
}
PHP does not process JSON requests automatically like it does with form-encoded or multipart requests. PHP不像处理表单编码或多部分请求那样自动处理JSON请求。 If you want to use JSON to send requests to PHP, you're basically doing it correctly with file_get_contents().
如果你想使用JSON向PHP发送请求,你基本上是使用file_get_contents()正确地执行它。 If you want to merge those variables into your global $_POST object you can, though I would not recommend doing this as it might be confusing to other developers.
如果你想将这些变量合并到你的全局$ _POST对象中,你可以,但我不建议这样做,因为它可能会让其他开发人员感到困惑。
// it's safe to overwrite the $_POST if the content-type is application/json
// because the $_POST var will be empty
$headers = getallheaders();
if ($headers["Content-Type"] == "application/json")
$_POST = json_decode(file_get_contents("php://input"), true) ?: [];
Quick note: you should not be sending a charset with your Content-Type for application/json. 快速注意:您不应该发送带有Content-Type for application / json的字符集。 This should only be sent with text/* Content-Types.
这应该只与text / * Content-Types一起发送。
You forgot to name your variables in the send function. 您忘了在send函数中命名变量。 The good way to use it is
使用它的好方法是
x.send('name1='+string+'&name2=value2');
Given that, I think you will have to change the content-length header. 鉴于此,我认为你将不得不改变内容长度标题。 I don't think it is usefull to send it.
我不认为发送它是有用的。
One another thing you can do is try with GET method. 您可以做的另一件事是尝试使用GET方法。 You can also try to change your content-type header by that one :
您还可以尝试通过以下方式更改内容类型标头:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.