php和JSON的帮助!

时间:2010-01-18 21:28:53

标签: php jquery json .post

我有一个用于更新数据库表的脚本。我需要返回一个JSON数组并使用JQUERY更新一些表。

我的php脚本:

$update = mysql_query("UPDATE PLD_SEARCHES SET STATUS = 1, TOTAL_RESULTS = ".$scrapper->getTotalResults().",RESULTS = $resultCounter WHERE ID = ".$searchId);
$output = array("status"=>"COMPLETED","results"=>$resultCounter,"totalResults"=>$scrapper->getTotalResults());
echo json_encode($output);

jquery代码:

$("button").live("click", function(event){
                    event.preventDefault();
                    $.getJSON("startsearch.php",{ searchId: $(this).val() }, function(data){
                        alert(data[0].status);
                    });

现在......问题是,如果我使用$.post("startsearch.php",{ searchId: $(this).val() }, function(data))脚本被执行,我得到一个值未定义的好警报。如果我添加参数“json”,脚本将不再执行。我试图使用getJSON但同样的问题。

有人有什么想法吗?我很绝望......这已经困扰了我差不多一个星期,我仍然无法解决它。

4 个答案:

答案 0 :(得分:0)

在您的php文件中,请确保设置正确的内容类型:

header("Content-type: application/json; charset=utf-8");

这样jquery可以正确eval对json对象的响应。

答案 1 :(得分:0)

您可以按如下方式获取您的回复数据:

alert(data.status);
alert(data.results);
alert(data.totalResults);

答案 2 :(得分:0)

请不要使用警报,将firebug安装到firefox中或在chrome或safari中启用javascript控制台。之后,您可以使用console.log(data);

我的猜测是数据不是数组。还可以查看jquery docs http://docs.jquery.com/Ajax/jQuery.getJSON

上的each()exmaple

答案 3 :(得分:0)

好吧,我相信json2.js要解析从AJAX请求返回的json数据。您可以从http://json.org下载。这个库提供了一种更好的方法来解析任何字符串,如果sting不在json中,它将抛出异常。

我总是写这样的AJAX请求:

$.post(URL,
  { PARAM },
  function(data){
    try {
      var r = JSON.parse(data);
      //this for your code above
      alert (r.status); //should be 'COMPLETED'
    }
    catch (e) {
      //data is not in json format, or there are another exception in try block
      //do something about it
      alert('Exception occured, please check the data!');
    }
});

处理json时,php中的数组将成为json中的变量成员。因此,如果在你的php中它是$output['status'],那么在json中,它将是r.status