从ajax调用函数调用代码并逐项显示

时间:2014-09-03 04:17:18

标签: javascript asp.net ajax

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

 [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>

3 个答案:

答案 0 :(得分:1)

尝试

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

答案 1 :(得分:1)

为了让您的jQuery工作,您还需要在C#代码中序列化List<person> -

而不是

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

答案 2 :(得分:0)

在success函数中尝试控制台日志记录(或F12 JavaScript调试)以查看响应对象及其成员。 [Object,object]应该是JavaScript尝试将对象(代码)转换为字符串失败。您可能会找到&#34;确切的值&#34;循环如此:

  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'];
    }
  }
相关问题