通过 AJAX/jQuery 发送多个 JSON 对象会返回一个"undefined"数组 (PHP)



目标

使用 jQuery 通过$.ajax()发送[{"ID": 1, "Name": "XBOX"}, {"ID": 2, "Name": "Playstation 3"}]

问题所在

我有这个:

[...]
var object = $.parseJSON(data);
$.ajax({
    type: "POST",
    url: "laboratory.php",
    data: object,
    success: function(response) {
        console.log(response);
    }
});

并且,在laboratory.php

<?php print_r($_REQUEST); ?>

最后,通过控制台返回的是:

Array
(
    [undefined] => 
)

这就是data变量的含义:

[{"ID": 1, "Name": "XBOX"}, {"ID": 2, "Name": "Playstation 3"}]

这就是object的意思(通过Chrome的控制台(:

[Object, Object]

有人可以给我一个想法吗?

你有没有尝试过使用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);
    }
});

问题来了。 将对象数组传递给$.param()(这是jQuery在内部使用非字符串data:所做的(会导致"undefined=undefined&undefined=undefined"这正是您从PHP返回的内容。你的数组只是采用jQuery无法理解的格式。由于您实际要发送的是 json,因此不要使用 $.parseJSON因为它会将您的 json 变成一个数组,而您真正想要的只是一个字符串。

//var object = $.parseJSON(data);
$.ajax({
    type: "POST",
    url: "laboratory.php",
    data: data,
    success: function(response) {
        console.log(response);
    }
});

对于多个数据,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.
            });
});

最新更新