无法将收到的JSON解码为数组

Luk*_*k4s 3 javascript php ajax post json

JS

从FORM序列化数据,将其字符串化并使用AJAX将其作为JSON发布到update.php

jQuery.fn.serializeObject = function () {
  var formData = {};
  var formArray = this.serializeArray();

  for(var i = 0, n = formArray.length; i < n; ++i)
    formData[formArray[i].name] = formArray[i].value;

  return formData;
};

$(function() {
    $('form').submit(function() {
        data = $('form').serializeObject();
        alert(JSON.stringify(data));   
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: 'inc/update.php',
            data: {json: JSON.stringify(data)},
            dataType: 'json'
        });  
    });
}); 
Run Code Online (Sandbox Code Playgroud)

update.php那里应该被解码为一个数组文件

$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array

$name = $response['name'];

$update = $pdo->prepare("UPDATE user SET name='".$name."' WHERE id='3';");
$update->execute();//the SQL works fine with String for $name
Run Code Online (Sandbox Code Playgroud)

使用Firefox中的Tamper Data插件我检查了POSTDATA,这里是:

json=%7B%22name%22%3A%22fff%22%7D
Run Code Online (Sandbox Code Playgroud)

这就像:

json={"name":"fff"}
Run Code Online (Sandbox Code Playgroud)

我是JS/AJAX/JSON的新手,我找不到自己的错误.所以请帮助我.
我搜索了好几个小时没有成功.

The*_*rot 5

serializeObject当你可以使用时,不知道写功能的重点是什么serializeArray.

使用Javascript:

$(function() {
    $('form').submit(function(e) {
        e.preventDefault(); // Stop normal submission, which is probably why your PHP code isn't working
        data = $('form').serializeArray();
        alert(JSON.stringify(data));   
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: 'inc/update.php',
            data: {
                json: JSON.stringify(data)
            },
            dataType: 'json'
        });  
    });
    return false;
});
Run Code Online (Sandbox Code Playgroud)

PHP:

$str_json = _$_POST['json'];
$response = json_decode($str_json, true); // decoding received JSON to array
$name = $response['name'];
Run Code Online (Sandbox Code Playgroud)

如果在其中使用true第二个参数,json_decode则返回一个数组而不是对象.所以你需要这样做

$name = $response['name'];
Run Code Online (Sandbox Code Playgroud)