对Json的回应感到沮丧

时间:2010-12-22 19:18:42

标签: c# asp.net json jquery

所以这是我的问题。我正在使用Jquery的$ .ajax将一系列值传回Web方法。 Web方法获取值,创建一个对象,然后将其作为json发送回调用页面。一旦我收到回复,我就无法访问响应并显示它的值。

任何人都可以解释我需要做些什么来使这项工作?

jquery脚本:

$(document).ready(function() {
    $("#create").click(function() {
        var name = $('#name').val();
        var company = $('#company').val();
        var location = $('#location').val();
        var phonenumber = $('#phonenumber').val();
        var country = $('#country').val();

        $.ajax({
            type: "POST",
            url: "WebService.asmx/MakeEmployee",
            data: "{name:'" + name +
                          "',company:'" + company +
                          "',location:'" + location +
                          "',phonenumber:'" + phonenumber +
                          "',country:'" + country +
                          "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                AjaxSucceeded(msg.d);
            }
        });
    });

    function AjaxSucceeded(data) {
        //var item = jQuery.parseJSON(data) // this doesn't work for me.
        $("#response").html(
            "<ul><li> " + data.Name +
            "</li><li> " + data.Company +
            "</li><li> " + data.Address +
            "</li><li> " + data.Phone +
            "</li><li> " + data.Country +
            "</ul> "
            );
        };
  });

网络方法:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string MakeEmployee(string name, string company, 
              string location, string phoneNumber, string country)
{
    Employee e = new Employee(name, company, location, phoneNumber, country);
    return new JavaScriptSerializer().Serialize(e);
}

我回复的回应:

{"d":"\"Name\":\"bob\",
          \"Company\":\"google\",
          \"Address\":\"home\",
          \"Phone\":\"123\",
          \"Country\":\"usa\"}"}

这是我认为我应该回来的:

{"Name":"bob",
     "Company":"google",
      "Address":"home",
      "Phone":"123",
      "Country":"usa"}

一旦页面再次渲染,我得到的错误是:

•undefined
•undefined
•undefined
•undefined
•undefined

3 个答案:

答案 0 :(得分:2)

您的响应已经被解析为JSON,所以它已经是一个对象......不需要再次解析它就像直接使用它一样,如下所示:

function AjaxSucceeded(data) {
    $("#response").html(
        "<ul><li> " + data.Name +
        "</li><li> " + data.Company +
        "</li><li> " + data.Address +
        "</li><li> " + data.Phone +
        "</li><li> " + data.Country +
        "</ul> "
    );
}

ASP.Net添加了{ d: ... }包装器,这是正常行为。之后您的问题是未正确返回的元素,您需要从ASP.Net返回对象而非字符串,最好是:

[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Employee MakeEmployee(string name, string company, 
  string location, string phoneNumber, string country) {
    return new Employee(name, company, location, phoneNumber, country);
}

...其中Employee在JavaScript端具有您想要的属性。让ASP.Net在这里处理序列化,而不是直接进行,你会得到一个更清晰的响应。

答案 1 :(得分:1)

首先清理您的服务方法。你真的不需要这个构造函数和所有这些属性。您已经拥有Employee类型,因此请使用它:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Employee MakeEmployee(Employee e)
{
    // Maybe do something more useful here with this employee
    // like raise his salary
    return e;
}

然后清理你的javascript:

$.ajax({
    type: 'POST',
    url: 'WebService.asmx/MakeEmployee',
    data: JSON.stringify({
        // All those correspond to Employee properties you would like to pass
        Name: $('#name').val(),
        Company: $('#company').val(),
        Location: $('#location').val(),
        PhoneNumber: $('#phonenumber').val(),
        Country: $('#country').val()
    }),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(msg) {
        // msg.d is gonna be the returned employee
        AjaxSucceeded(msg.d);
    }
});

答案 2 :(得分:1)

尝试将此ajax initaliazer功能用于asp.net ajax。它设置了大多数默认值,因此您只需提供url / params 只需先调用document.ready()函数,然后调用你的电话。

function jqueryInit() {
$.ajaxSetup({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: "{}",
    dataFilter: function (data) {
        var msg;
        if (typeof (JSON) !== 'undefined' &&
                typeof (JSON.parse) === 'function')
            msg = JSON.parse(data);
        else
            msg = eval('(' + data + ')');

        if (msg.hasOwnProperty('d'))
            return msg.d;
        else
            return msg;
    }
});

}