0

In Javascript I'm creating an array for a user side list

var dataArr = [];
 $("#sortable li").each(function(idx, elem) {
    dataArr[idx] = $(elem).html();
});
alert(dataArr[0]);

This is working as expected and will alert the first item in the list. "Frank" or whatever it may be.

$.ajax({
url: "fiddle.php",
type: "POST",
data: "dataArr="+dataArr,
success: function(response) {
alert(response);}

I send this array over to PHP and the ajax test confirms its retrieved from a var_dump on the other side.

echo ($_POST['dataArr'][1]);

The problem occurs here when trying to output a particular item, in this case the 2nd item which may be "John" it'll instead output the 2nd character in the first item "r". This is appearing in the Ajax test window. I'm looking for the whole word instead. Is it a syntax error or a problem with how the data is passed?

4

2 回答 2

2

我认为问题与您如何在 ajax 调用中发送数据有关。

尝试这个:

JS

var dataArr = [];
 $("#sortable li").each(function(idx, elem) {
    dataArr[idx] = $(elem).html();
});


$.ajax({
    url: "fiddle.php",
    type: "POST",
    data: dataArr, //Send just the array
    success: function(response) {
        alert(response);
    }
});

PHP

var_dump($_POST['dataArr']);
于 2013-05-11T17:29:59.927 回答
1

这是因为您的数组正在转换为字符串形式。

JSON.stringify()在客户端和json_decode服务器端执行

喜欢

在ajax调用中

data: "dataArr="+JSON.stringify(dataArr),

并在 php 代码中

$dataArr = json_encode($_POST['dataArr']);
var_dump($dataArr);
于 2013-05-11T17:31:18.460 回答