AJAX请求INSERT和UPDATE不起作用

时间:2012-12-02 21:45:16

标签: php jquery ajax json mysqli

有人可以告诉我为什么这个AJAX Post请求无效。发送的默认listId为0. savedList由ListJSON和ListName组成。代码如下。

$.post('save.php', {"id":listId, "list":JSON.stringify(savedList), 
function(savedListId) {
    listId = savedListId;
    alert('List saved');
    // Refresh to a) get out of edit mode and b) give a bookmarkable URL
    window.location = 'list.html?id='+listId;
});

服务器端如下:

if(empty($_POST['list'])) {
header('HTTP/1.0 400 Bad Request', true, 400);
exit('No list sent');
}

if( ! $decodedList = json_decode($_POST['list'])) {
header('HTTP/1.0 400 Bad Request', true, 400);
exit('List does not decode');
}


if(empty($_POST['id']) || $_POST['id']=="null") {
$sql = "INSERT INTO Lists SET ListJSON = ?, ListName = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("ss", $_POST['list'], $decodedList->listName); 
$query->execute();


header('Content-type: application/json');
exit('"'.$mysqli->insert_id.'"');
} else {
$sql = "UPDATE Lists SET ListJSON = ?, ListName = ? WHERE ListID = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("ssi", $_POST['list'], $decodedList->listName, $_POST['id']);

$query->execute();


header('Content-type: application/json');
exit('"'.(int)$_POST['id'].'"');
}

1 个答案:

答案 0 :(得分:0)

尝试在(int)前添加$_POST['id']。我相信javascript是以字符串形式发送id,但是你试图用mysqli将它更新为int。