[英]Sending object as param with Javascript xhr
I have an array that has a structure similar to the following: 我有一个数组,其结构类似于以下内容:
var data = [
{
'name': 'Foo'
},
{
'name': 'Bar'
}
]
And I want to pass it to my php script with pure Javascript without relying on jQuery. 而且我想使用纯Javascript将其传递给我的php脚本,而不依赖jQuery。
So my jQuery version would be: 所以我的jQuery版本是:
$.ajax({
'url': '/script.php',
'method': 'POST',
'data': {'inscriptions': data},
'dataType': 'json',
'success': function(response){
// my code for handling the response
}
});
And in Javascript I have the following: 在Javascript中,我有以下内容:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/script.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
xhr.onreadystatechange = function(event){
if(event.target.readyState != XMLHttpRequest.DONE)
return;
// my code for handling the response
};
However the issue I'm having is that sending it this way in Javascript, my $_POST
on the server side is empty because the 但是我遇到的问题是在Java中以这种方式发送它,我在服务器端的
$_POST
为空,因为
array(0){}
And if I change it to: 如果我将其更改为:
xhr.send(JSON.stringify({'inscriptions': data}));
Then on my server side my $_POST
will be: 然后在我的服务器端,我的
$_POST
将是:
array (size=1)
'{"inscriptions":' =>
array (size=1)
'{"name":"Foo"},{"name":"Bar"}' => string '' (length=0)
When I send it via jQuery I get the following: 当我通过jQuery发送它时,我得到以下信息:
array (size=1)
'inscriptions' =>
array (size=2)
0 =>
array (size=1)
'name' => string 'Foo' (length=3)
1 =>
array (size=1)
'name' => string 'Bar' (length=3)
Is there a way to achieve the same thing with pure Javascript? 有没有办法用纯Javascript实现相同的目的?
My questions has been marked as a duplicate of Send JSON data from Javascript to PHP? 我的问题被标记为将JSON数据从Javascript发送到PHP? but the answer doesn't answer my question.
但是答案没有回答我的问题。 They are using a way to 'bypass' it with:
他们正在使用一种“绕过”它的方式:
php://input
However, it's not sending it directly to the $_POST
like jQuery does. 但是,它没有像jQuery那样直接将其发送到
$_POST
。
xhr.setRequestHeader("Content-type", "application/json")
xhr.send(JSON.stringify({'inscriptions': data}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.