JQUERY - 通过 Ajax 将数组发送到 PHP(我知道这个问题已经处理了很多..)


JQUERY - Send Array through Ajax to PHP (I know the issue has been treated a lot...)

我想将我在Jquery脚本中创建的数组发送到php文件。我知道这个问题已经处理了很多。不幸的是,在应用似乎是最佳实践时,我无法使其正常工作。希望有人能帮助我。提前谢谢你。干杯。马克。下面是我的代码:

我的JS:

// I build myArray
var myArray = new Array();
$('.someClass').each(function() {
    $this = $(this);
    myArray.push({
        'id': $this.attr('attrId')
    });
});
//...and then send it to myFile.php
var ajaxData = { myArray: JSON.stringify(myArray) };
$.ajax({
    type: "POST",
    url: "myFile.php",
    data: ajaxData,
    success: function(data) {
        $('body').append(data);
    }
});​

我的PHP:

$myArray = json_decode(stripslashes($_POST['myArray']));
foreach($myArray as $value){
    echo $value.'</br>';
}

我得到的错误:

Catchable fatal error:  Object of class stdClass could not be converted to string

尝试替换此行:

$myArray = json_decode(stripslashes($_POST['myArray']));

有了这个:

$myArray = json_decode(stripslashes($_POST['myArray']), true);

如果 json_decode() 的第二个参数设置为 true,则所有对象都将转换为关联数组:http://php.net/manual/en/function.json-decode.php