通过jQuery获取数组AJAX调用不起作用

时间:2014-07-14 15:20:08

标签: php jquery ajax

我有以下代码:

 var data = $(this).sortable('serialize');
$.ajax({
                    data: {order: data, actionFor: 'main_articles'},
                    type: 'POST',
                    url: 'updateDisplayOrder.php',
                    success: function (msg) { //re-number the rows from 1 to n
                       //code goes here
                    },
                    error: function () {
                        alert("An error occurred");
                    });

PHP:

    require_once('../lib/common/db_connect.php');
    $ids = array();
    $actionFor = $_POST['actionFor'];
    foreach ($_POST['order'] as $value) //error here {
    //more code goes here
    }

问题是我在foreach行上遇到了这个错误:

  

警告:为foreach()提供的参数无效

我注意到如果我改变这一行:

 data: {order: data, actionFor: 'main_articles'}, 

data:data

在PHP中:

foreach ($_POST['order'] as $value) //error here {

foreach ($_POST['item'] as $value)

它很棒。 为什么?我怎么能狐狸呢?谢谢!

1 个答案:

答案 0 :(得分:1)

$_POST['order']包含一个字符串,而不是一个数组。您需要先将字符串解析为数组。试试这个:

$order = array();
$stg1 = explode("&", $_POST['order']);
$i = 0;
foreach($stg1 as $keyval) {
    list($key, $val) = explode("=", $keyval);
    $order[$i++] = $val;
}

然后你可以随意做foreach($order as $value)