小编典典

对Json回应感到沮丧

json

所以这是我的问题。我正在使用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

阅读 244

收藏
2020-07-27

共1个答案

小编典典

您的响应已经被解析为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> "
    );
}

{ d: ... }包装是由ASP.Net,这是正常的行为增加。之后,您的问题是元素未正确返回,则需要从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在这里处理序列化而不是直接进行序列化,您将获得总体上更清晰的响应。

2020-07-27