2013-03-07 69 views
1

請幫我修復這個json對象。我被卡在這裏,無法弄清楚。jquery什麼是正確的json對象來解析

我得到一個json對象(但我不確定它是否正確)。我正在嘗試4種方法來顯示json的結果,但沒有任何工作。請幫我看看,我做錯了什麼

這裏是的WebMethod C#

return_str += "{'id':'" + p_id + "','firstname':'" + firstname + "','lastname':'" + lastname + "','prefix':'" + prefix + "','gender':'" + gender + "','mobilephone':'" + mobilephone + "','email':'" + email + "','diplomano':'" + diplomano + "'}"; 

這裏創建JSON對象,試圖獲得JSON和顯示結果的jQuery代碼

$('#btn_second').click(function() { 
      //$('#txt_isim_4').val('test arif'); 
      $.ajax({ 
       type: "POST", 
       url: "Registration.aspx/get_selected_professional", 
       data: "{'id':'2'}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function (data) { 
        alert('1:' + data); // shows "[object Object]" 
        alert('2:' + data.id); // shows "undefined" 
        alert('3:' + data.d); // shows json string 
        var json = $.parseJSON(data); 
        alert('4:' + json.id); // doesnt show the alert box, I think It throws and error 
       } 
      }); 

我如何顯示名字? });

+1

驗證您的JSON here.http://jsonlint.com – 2013-03-07 12:51:20

+0

實際的JSON是什麼樣的? – fguchelaar 2013-03-07 12:52:13

+0

爲什麼你要手動解析?你聽說過JSON seralizer嗎?使用JSON.Net – 2013-03-07 12:54:43

回答

1

當您使用Web服務,所以你將不得不去爲data.d

$('#btn_second').click(function() { 
     //$('#txt_isim_4').val('test arif'); 
     $.ajax({ 
      type: "POST", 
      url: "Registration.aspx/get_selected_professional", 
      data: "{'id':'2'}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (data) { 
       alert(data.d.id); 

      } 
     }); 

的正確方法是這樣的

$('#btn_second').click(function() { 
     //$('#txt_isim_4').val('test arif'); 
     $.ajax({ 
      type: "POST", 
      url: "Registration.aspx/get_selected_professional", 
      data: "{'id':'2'}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (data) { 
       data=$.parseJSON(data.d); 
       alert(data.id); 

      } 
     }); 
-1

'不是JSON有效,使用" +代替#

這應該工作:

return_str += "{\"id\":\"" + p_id + "\",\"firstname\":\"" + firstname + "\",\"lastname\":\"" + lastname + "\",\"prefix\":\"" + prefix + "\",\"gender\":\"" + gender + "\",\"mobilephone\":\"" + mobilephone + "\",\"email\":\"" + email + "\",\"diplomano\":\"" + diplomano + "\"}"; 

從json.org:

值可以是在雙串引號,或一個數字,或者真或 false或null,或者一個對象或數組。這些結構可以是嵌套的 。

+0

應該使用方括號嗎? – 2013-03-07 12:54:41

+0

不,大括號ara ok – Stefan 2013-03-07 12:55:19

+0

我按照你告訴我的方式做了。現在如何顯示數據,我應該使用data.firstname? – 2013-03-07 12:55:53