php json_decode和Jquery Nestable

时间:2014-01-20 19:10:28

标签: php jquery jquery-nestable

我正在使用jquery Nestable(http://dbushell.github.io/Nestable/)。

当我改变我的可嵌套元素的顺序时,我正试图拦截它的数据。

$('.dd').nestable().on('change', function() {
  var json_text = $('.dd').nestable('serialize');
  $.post("/includes/processes/core.php", {
    cmd: 'nestable',
    table: table,
    data: json_text
  }, function(response){
    alert(response);
  });
});

在core.php中,我完成了:

$data = $_POST['data'];
$data = json_decode($data, true);
function parseJsonArray($jsonArray, $parentID = 0) {
  $return = array();
  foreach ($jsonArray as $subArray) {
    $returnSubSubArray = array();
    if (isset($subArray['children'])) {
  $returnSubSubArray = parseJsonArray($subArray['children'], $subArray['id']);
    }
    $return[] = array('id' => $subArray['id'], 'parentID' => $parentID);
    $return = array_merge($return, $returnSubSubArray);
  }
  return $return;
}

$readbleArray = parseJsonArray($data);

我要操纵这个数组,但我不能继续,因为响应是:

"json_decode() expects parameter 1 to be string, array given in core.php on line (where is "$data = json_decode($data, true;")"

如果我用json_encode($ data)更改json_decode($ data,true),这就是响应:

"Invalid argument supplied for foreach() in core.php on line (where is "foreach ($jsonArray as $subArray);")"

请帮助我..

2 个答案:

答案 0 :(得分:1)

使用JSON.stringify。它会将您的javascript对象转换为JSON字符串,允许您发布它:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

你可以在PHP中解码它。为此,在您的jQuery代码中替换为:

data: json_text

使用:

data: {json_text: JSON.stringify(json_text)}

答案 1 :(得分:1)

尝试删除此行,因为$ .post不执行json编码。

$data = json_decode($data, true);