我正在尝试创建一个关联数组,其中记录ID为键,顺序为值。然后我想通过ajax传递给php,我将通过数组并更新记录。但是它无法正常工作我似乎在json_decode($ _ REQUEST ['orderArray'],true)中得到null;
代码有什么问题:
jquery:
//Make project task table rows sortable
$('#Task_table tbody').sortable({
items: "tr:not(.disable_sort)",//disable sortable on header row
helper: fixHelperModified, //call helper function
update: function(event, ui) {
var order = {};//create object
$('#Task_table tr').each(function(){//loop through rows
var id = $(this).children('td:first-child').find(".order_number").attr("rel");
var order_number = $(this).children('td:first-child').find(".order_number").val();
//fill object array with keys(task->id) and values (task->order_number)
order[id] = order_number;
});
//convert array to json
var jsonArray = JSON.stringify(order);
//prepare POST data
var dataString = { 'orderArray':jsonArray };
$.ajax({
type: "POST",
url: "index.php?module=Project&action=update_order",
data: dataString,
success: function() {
// location.reload();
}
});
}
});
这通过帖子发送: orderArray {“4b0df1da-8b2d-7776-0026-52d0b3cefbfa”:“3”,“161699ae-6db0-43d6-e85b-52ca07767b0f”:“1”,“8da4cfc3-b56d-12da-e34c-52d09ed0b310”:“2”}
php:
//updates the order of the tasks
function action_update_order(){
//create object/array from json data
$orderArray = json_decode($_REQUEST['orderArray'], true);
var_dump($orderArray);
foreach($orderArray as $id => $order_number){
$GLOBALS['log']->fatal('order: '.$order_number[$id]);
$task = new ProjectTask();
$task->retrieve($id);
$task->order_number = $order_number;
$task->save();
}
}
正如我所说,我似乎无法通过jasondecode的结果进行预测。也很难调试它的ajax。
答案 0 :(得分:1)
var dataString = { 'orderArray':jsonArray };
到
var dataString = { 'orderArray': order };
答案 1 :(得分:0)
由于某种原因,JSON.stringify(order)正在添加“我的字符串的Html实体版本,所以我需要在我的php中首先使用htmlspecialchars_decode();在json_decode之前。它似乎有效。