[英]Send multiple JSON objects through AJAX/jQuery returns me an “undefined” array (PHP)
Send [{"ID": 1, "Name": "XBOX"}, {"ID": 2, "Name": "Playstation 3"}]
via $.ajax()
using jQuery. 使用jQuery通过
$.ajax()
发送[{"ID": 1, "Name": "XBOX"}, {"ID": 2, "Name": "Playstation 3"}]
。
I have this: 我有这个:
[...]
var object = $.parseJSON(data);
$.ajax({
type: "POST",
url: "laboratory.php",
data: object,
success: function(response) {
console.log(response);
}
});
And, in laboratory.php
: 并且,在
laboratory.php
:
<?php print_r($_REQUEST); ?>
And finally, the return via console is: 最后, 通过控制台返回的结果是:
Array
(
[undefined] =>
)
This is what the data
's variable means: 这就是
data
变量的含义:
[{"ID": 1, "Name": "XBOX"}, {"ID": 2, "Name": "Playstation 3"}]
And this is what object
means (by Chrome's console): 这就是
object
含义(通过Chrome的控制台):
[Object, Object]
Can someone give me an idea? 有人可以给我一个主意吗?
have you tried using JSON.stringify: 您是否尝试过使用JSON.stringify:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
$.ajax({
type: "POST",
contentType: 'application/json',
url: "laboratory.php",
data: JSON.stringify(object), // using stringify
success: function(response) {
console.log(response);
}
});
Here's the problem. 这是问题所在。 passing your array of objects to
$.param()
(which is what jQuery does internally with data:
that isn't a string) results in "undefined=undefined&undefined=undefined"
which is exactly what you are getting back from php. 将您的对象数组传递给
$.param()
(这是jQuery在内部对data:
这不是字符串)会导致"undefined=undefined&undefined=undefined"
,这正是您从php中获取的内容。 Your array simply is in a format that jQuery can't understand. 您的数组只是jQuery无法理解的格式。 Since what you actually want to send is json, don't use
$.parseJSON
because it'll turn your json into an array and what you really want is just a string. 由于您实际要发送的是json,因此请不要使用
$.parseJSON
因为它将把您的json转换为数组,而您真正想要的只是一个字符串。
//var object = $.parseJSON(data);
$.ajax({
type: "POST",
url: "laboratory.php",
data: data,
success: function(response) {
console.log(response);
}
});
For multiple data, getJSON is better in my opinion: 对于多个数据,我认为getJSON更好:
$.getJSON('laboratory.php', function(json) {
$.each(json, function(key, val) {
//Getting the value of id
val["ID"];
//Getting the value of name
val["NAME"];
//DO whatever u want.
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.