jquery什么是正确的json对象来解析

问题描述:

请帮我修复这个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

当您使用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); 

      } 
     }); 

'不是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