2012-02-06 40 views
0

我正在构建一个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) 
     } 
    } 
); 

响应“插件/ validate_event.php”将是这样的:{}(空==成功)或像这样:

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

基本上,我有一个PHP脚本,检查是否我们可以添加事件,如果是这样,则返回一个empty阵列。否则,它将返回一个包含dates的数组,格式为yyyymmdd,每个日期都有一个可用hours的数组,其格式为hhmm

但我的问题是,当我尝试遍历数组,alert(response)给我的PHP的答案{"20120106":[1300,143 ....alert(htmlresponse)给了我这样的:

0: {1: "2: 23: 04: 15: 26: 07: 18: 09: 310: "11: :12: [13: "14: 015: 916: 017: 018: "19: ,20: 121: 022: 423: 024: ,25: "26: 127: 128: 029: 030: "31: ,32: 133: 034: 235: 036: ,37: 138: 139: 040: 541: ,42: 143: 044: 245: 546: ,47: 148: 149: 150: 051: ,52: 153: 054: 355: 056: ,57: 158: 159: 160: 561: ,62: 163: 064: 365: 566: ,67:......

我缺少什么?

非常感谢

乔尔

回答

1

如果你想和$ .get/$。张贴到自动解析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 
); 
+0

添加','json''完美工作,非常感谢! – Joel 2012-02-06 04:30:48

0

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

+0

非常感谢,我会牢记这一点! – Joel 2012-02-06 04:31:13