Jquery $ .post以JSON格式返回数据,无法正确迭代数据?

时间:2012-02-06 03:13:29

标签: jquery json

我正在构建一个Web日历应用程序,我正在尝试添加一个功能,在发送表单之前检查数据库,看看我们是否可以添加日历事件。

现在我有这个脚本尝试从PHP文件中获取响应:

// send form data using ajax requests
$.post(
    "addons/validate_event.php", 
    $("#modif_inventaire").serialize(), 
    function(response){      

        if (response) {

            var htmlresponse = "";

            $.each(response, function(key, value) { 
              htmlresponse += key + ': ' + value; 
            });

            alert(response)
            alert(htmlresponse)
        }
    }
);

响应“addons / validate_event.php”将如下所示:{}(空==成功)或者像这样:

{"20120106":[1300,1430,1510,"1600"],"20120107":["0900",1000,"1100","1200","1300","1400","1500"]}

基本上,我有一个PHP脚本,检查我们是否可以添加事件,如果是,它返回一个empty数组。否则,它会以[{1}}格式返回包含dates的数组,并且每个日期都有一个格式为yyyymmdd的可用hours数组。

但我的问题是,当我尝试迭代数组时,hhmm给了我答案alert(response),但{"20120106":[1300,143 ....给了我这个:

alert(htmlresponse)

我错过了什么?

非常感谢

乔尔

2 个答案:

答案 0 :(得分:1)

如果您想要$ .get / $ .post自动解析JSON响应,您需要传入' json'作为第四个论点,如下:

// send form data using ajax requests
$.post(
    "addons/validate_event.php", 
    $("#modif_inventaire").serialize(), 
    function(response){      

        if (response) {

            var htmlresponse = "";

            $.each(response, function(key, value) { 
              htmlresponse += key + ': ' + value; 
            });

            alert(response)
            alert(htmlresponse)
        }
     }, 'json' // this argument is needed so jquery will treat response as JSON object and not text
);

答案 1 :(得分:0)

处理你回调json数据。我有一个好习惯。希望对你有所帮助。
第1步:$.trim(data);
步骤2:var obj = jQuery.parseJSON(data);
第3步:处理您的代码。

相关问题