无法处理jquery ajax发送的json

时间:2012-12-22 07:51:22

标签: php mysql jquery

我似乎无法让以下工作

restoJSON = { "name" : "Bloesem", "qName" : "bloesem", "address" : "Binnen Dommersstraat 13", "area" : "Jordaan", "tel" : "770 0407", "cuisine" : "European", "comment" : "Ver``rassingsmenu - slow service but 'gezellig' atmosphere", "booking" : "", "website" : "http://www.restaurantbloesem.nl/", "link" : "/?p=6", "rating" : 3, "price" : "3", "lat" : "52.382917", "lng" : "4.8854370000000245", "heading" : "0", "pitch" : "0", "zoom" : "0" };

     jQuery.ajax({
       type: "POST",
       url: "updateDatabase.php",
       data: restoJSON,
       dataType: "text",
       success: function(response, stat)
       {
         console.log("Response: " + response);
       },
       error: function()
        {
           console.log(arguments);
        }       
     });

然后updateDatatbase.php在这些行上有变化用于调试

echo "name: " . $_POST['qName'];
$json = json_decode($_POST['data'], true);
echo " " . $json['qName'];
foreach($_POST as $key=>$val) {
echo $key . "-x-" . $val;
}

我是一个相对不高兴的人,通过从这个论坛复制建议来完成工作,而不是完全理解。控制台日志位于下方 - 注意它如何拆分链接行中的=

Response: name: 
{"name":"Bloesem",
"qName":"bloesem",
"address":"Binnen_Dommersstraat_13",
"area":"Jordaan",
"tel":"770_0407",
"cuisine":"European",
"comment":"Verrassingsmenu_-_slow_service_but_'gezellig'_atmosphere",
"booking":"",
"website":"http://www_restaurantbloesem_nl/",
"link":"/?p-x-6\",
\"rating\" : 3,
\"price\" : \"3\",
\"lat\" : \"52.382917\",
\"lng\" : \"4.8854370000000245\",
\"heading\" : \"0\",
\"pitch\" : \"0\",
\"zoom\" : \"0\"
}

2 个答案:

答案 0 :(得分:0)

如果你看一下你的代码就会回显两个字符串。您需要删除其中一个,最有可能是echo $query;

所以尝试改变:

echo "name: " . $json['qName'];
echo $query;

只是:

echo "name: " . $json['qName'];

您还错过了restoJSON末尾的分号,并且未使用var将其声明为变量。

改变这个:

restoJSON = { "name" : "Bloesem", "qName" : "bloesem", "address" : "Binnen Dommersstraat 13", "area" : "Jordaan", "tel" : "770 0407", "cuisine" : "European", "comment" : "Ver``rassingsmenu - slow service but 'gezellig' atmosphere", "booking" : "", "website" : "http://www.restaurantbloesem.nl/", "link" : "/?p=6", "rating" : 3, "price" : "3", "lat" : "52.382917", "lng" : "4.8854370000000245", "heading" : "0", "pitch" : "0", "zoom" : "0" }

要:

var restoJSON = { "name" : "Bloesem", "qName" : "bloesem", "address" : "Binnen Dommersstraat 13", "area" : "Jordaan", "tel" : "770 0407", "cuisine" : "European", "comment" : "Ver``rassingsmenu - slow service but 'gezellig' atmosphere", "booking" : "", "website" : "http://www.restaurantbloesem.nl/", "link" : "/?p=6", "rating" : 3, "price" : "3", "lat" : "52.382917", "lng" : "4.8854370000000245", "heading" : "0", "pitch" : "0", "zoom" : "0" };

最后,您将数据作为key/value对发送,因此没有理由json_decode()他们。

改变这个:

$json = json_decode($_POST['data'], true);

要:

$json = $_POST;

答案 1 :(得分:0)

当通过jQuery.ajax发送数据时,POST变量被设置为restoJSON中的键/值。因此,在PHP中不需要JSON解码。只需简单地做:

echo "name: " . $_POST['qName'];

要查看'qName'已通过。此外,您的UPDATE语句当前未设置任何字段(请参阅:PHP Update Syntax)。