2012-02-06 72 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