2014-09-03 22 views
0

我正在调用来自ajax调用函数的代码。 我刚刚创建了一个Post方法,它返回一个列表。 我只想检查客户端的值。因此,只需输出一条警报消息并将response.d作为参数传递。但它返回object,Object而不是实际值。 我想知道获取值的确切方法吗?来自ajax调用的函数背后的调用代码并逐项显示

[WebMethod] 
     public static List<person> Post() 
     { 
      List<person> List = new List<person>(); 
      person p1 = new person(); 
      p1.name = "Sourav"; 
      p1.surname = "Kayal"; 
      List.Add(p1); 
      person p2 = new person(); 
      p2.name = "Sourav"; 
      p2.surname = "Kayal"; 
      List.Add(p2); 
      return List; 
     } 
    } 
    public class person 
    { 
     public string name { get; set; } 
     public string surname { get; set; } 
    } 


<script> 

    $(document).ready(function() { 

     $.ajax({ 
      type: "POST", 
      url: "JavaScript.aspx/Post", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (response) { 
       var names = response.d; 
       alert(names); 
      }, 
      failure: function (response) { 
       alert(response.d); 
      } 
     }); 
    }); 
</script> 
+0

您需要解析JSON对象获得值.. – Murtaza 2014-09-03 04:22:12

回答

1

为了您的jQuery的工作,你将需要系列化你List<person>在C#代码,以及 -

代替

return List; 添加下面的代码 -

//Add the below using line on the top of the page where all using directives are present 
using System.Web.Script.Serialization; 


var jsonSerialiser = new JavaScriptSerializer(); 
var json = jsonSerialiser.Serialize(List); 
return json; 

由于您使用jQuery的 - 我们可以使用下面的代码来解析JSON对象 -

$(document).ready(function() { 
    $.ajax({ 
     type: "POST", 
     url: "JavaScript.aspx/Post", 
     contentType: "application/json; charset=utf-8", 
     dataType: "text", 
     success: function (response) { 
      var obj = jQuery.parseJSON(response); 
      alert(obj.name); 
      alert(obj.surname); 
     }, 
     failure: function (response) { 
      alert(response.d); 
     } 
    }); 
}); 

随着你的成功的功能这上面的代码更改,您应该从JSON对象中的值。

编辑基于评论: 下面的线 -

var json = jsonSerialiser.Serialize(List); 

Produces string value of:  
[ 
    {"name":"Sourav","surname":"Kayal"}, 
    {"name":"Sourav","surname":"Kayal"}, 
] 

参考示例的详细信息 - CLICK HERE

+0

应该是什么返回类型为“返回json”? – 2014-09-03 06:10:33

+0

它应该是'string'。 – Murtaza 2014-09-03 06:17:45

+0

在“var obj = jQuery.parseJSON(response);”时出错 “Microsoft JScript运行时错误:无效字符” 使用JQuery版本: 2014-09-03 06:28:10

0

在成功函数中尝试控制台日志记录(或F12 JavaScript调试)以查看响应对象及其成员。 [对象,对象]应该是JavaScript尝试将对象(代码)翻译为字符串时失败。你可能会发现“精确值”的循环,像这样:

var surnames = [], prop, i; 
    for (item in response) { 
    if (item.hasOwnProperty('surname')) { 
     surnames.push(item.surname); 
    } 
    } 
    // Or 
    for(var i = 0; i < response.length; i++) { 
    if(typeof response[i]['surname'] === 'string') { 
     surnames[i] = response[i]['surname']; 
    } 
    } 
1

尝试

var names = JSON.parse(response); 
       alert(names.d); 
       alert(names.name); 
       alert(names.surname);