2013-10-22 15 views
1

由於某些原因,.done()函數在成功的AJAX調用後未觸發。這是JavaScript文件:jQuery AJAX .done未針對JSON數據觸發

//Create groups 
$("#compareschedulesgroups_div").on('click', '.compareschedules_groups', function() { //When <li> is clicked 
    //Get friendids and friend names 
    print_loadingicon("studentnames_taglist_loadingicon"); 
    $.ajax({ 
     type: "POST", //POST data 
     url: "../secure/process_getgroupdata.php", //Secure schedule search PHP file 
     data: { groupid: $(this).find(".compareschedules_groups_groupnum").val() }, //Send tags and group name 
     dataType: "JSON" //Set datatype as JSON to send back params to AJAX function 
    }) 
    .done(function(param) { //Param- variable returned by PHP file 
     end_loadingicon("studentnames_taglist_loadingicon"); 
     //Do something 
    }); 
}); 

Safari的網絡發展論壇標籤說,我的外部PHP文件回到這一點,這是正確的數據:

{"student_id":68,"student_name":"Jon Smith"}{"student_id":35,"student_name":"Jon Doe"}{"student_id":65,"student_name":"Jim Tim"}{"student_id":60,"student_name":"Jonny Smith"} 

的PHP文件看起來是這樣的。基本上,它得到一個json_encoded值,回顯一個Content-Type頭,然後回顯json_encoded值。

for ($i = 0; $i<count($somearray); $i++) { 
     $jsonstring.=json_encode($somearray[$i]->getjsondata()); 
    } 

    header("Content-Type: application/json", true); 
    echo $jsonstring; 

編輯:我有一個對象數組 - 這是去json_encoding它的方式嗎?

的getjsondata功能是這樣的,從另一個堆棧溢出問題:

public function getjsondata() { 
     $var = get_object_vars($this); 
     foreach($var as &$value){ 
      if(is_object($value) && method_exists($value,'getjsondata')){ 
       $value = $value->getjsondata(); 
      } 
     } 
     return $var; 
    } 
+0

這不是有效的JSON ...顯示更多你的PHP –

+0

作爲後續Kevin的評論,請查看http://jsonlint.com以驗證您的數據。 –

回答

2

你的循環調用json_encode(),輸出單個對象。當它們串聯在一起時,這是無效的JSON。解決方案是將每個對象附加到一個數組,然後編碼最後一個數組。 PHP的更改爲:

$arr = array(); 

for ($i = 0; $i<count($somearray); $i++) { 
    $arr[] = $somearray[$i]->getjsondata(); 
} 

header("Content-Type: application/json", true); 
echo json_encode($arr); 

這將輸出對象的數組例如JSON表示:

[ 
    { 
     "student_id": 68, 
     "student_name": "Jon Smith" 
    }, 
    { 
     "student_id": 35, 
     "student_name": "Jon Doe" 
    }, 
    { 
     "student_id": 65, 
     "student_name": "Jim Tim" 
    }, 
    { 
     "student_id": 60, 
     "student_name": "Jonny Smith" 
    } 
] 
+0

哦哇,這是愚蠢的 - 謝謝你的答案 - 我會在幾分鐘內接受它 – user2415992