2014-12-31 74 views
0

我有一個jQuery Post到PHP頁面並生成JSON響應。它成功生成JSON,因爲我已經顯示了整個響應。但是,每件事我都無法讓它警覺。任何想法讚賞。謝謝。 JSON的樣子:jquery post與JSON響應工作

[{"Part_Field":"Part_Note:3","Part_Value":"ValueofPart"},{"Part_Field":"Ft_In:3","Part_Value":"12"}, ... 

的jQuery:

$.post('/scripts/update_detail.php' , field_id + "=" + value, function(data){ 
       var d = document.getElementById("displayjson"); 
       d.innerHTML = data; 

       $.each(data, function(key, value) { 
        alert(value.Part_Field); 
       }); 


    }); 
+1

是否確定了jQuery知道它是JSON? 'console.log(typeof data);'它顯示字符串? – epascarello

+0

'console.log(data)',看看它是一個字符串還是一個數組。除非Content-Type頭是'application/json',否則它可能是一個字符串。 –

+1

謝謝,它是一個字符串。我不得不對數據運行jQuery.parseJSON到一個新的變量。感謝幫助! –

回答

0

你忘了在結束的字符串},"json");

改正的代碼應該是:

$.post('/scripts/update_detail.php' , field_id + "=" + value, function(data){ 
       var d = document.getElementById("displayjson"); 
       d.innerHTML = data; 

       $.each(data, function(key, value) { 
        alert(value.Part_Field); 
       }); 


    },"json"); // Here, you need to tell jQuery that whatever response 
// we are getting from server is a JSON string, in your case, 
//it was considering it as a string.