gpt4 book ai didi

jquery - WebMethod 返回 JSON,但我的 $.ajax() 回调中的响应 obj 只是一个字符串

转载 作者:行者123 更新时间:2023-12-03 22:30:32 24 4
gpt4 key购买 nike

这是我自制的序列化类:

public class JsonBuilder
{
private StringBuilder json;

public JsonBuilder()
{
json = new StringBuilder();
}

public JsonBuilder AddObjectType(string className)
{
json.Append("\"" + className + "\": {");
return this;
}

public JsonBuilder Add(string key, string val)
{
json.AppendFormat("\"{0}\":\"{1}\",", key, val);
return this;
}

public JsonBuilder Add(string key, int val)
{
json.AppendFormat("\"{0}\":{1},", key, val);
return this;
}

public string Serialize()
{
return json.ToString().TrimEnd(new char[] { ',' }) + "}";
}
}

这是网络方法

[WebMethod]
public static string GetPersonInfo(string pFirstName, string pLastName)
{
var json = new JsonBuilder().AddObjectType("Person");
json.Add("FirstName", "Psuedo" + pFirstName).Add("LastName", "Tally-" + pLastName);
json.Add("Address", "5035 Macleay Rd SE").Add("City", "Salem");
json.Add("State", "Oregon").Add("ZipCode", "97317").Add("Age", 99);
return json.Serialize();
}

Ajax调用客户端

 $.ajax(
{
type: "POST",
url: "Default.aspx/GetPersonInfo",
data: JSON.stringify(name),
contentType: "application/json; charset=uft-8",
dataType: "json",
success: function (rsp) { SetPerson(rsp); },
error: function (rsp)
{
alert(rsp);
}
});

最后是我的回调方法

function SetPerson(rsp)
{
$('#fName').val(rsp.d.FirstName);
$('#lName').val(rsp.d.LastName);
$('#address').val(rsp.d.Address);
$('#city').val(rsp.d.City);
$('#state').val(rsp.d.State);
$('#zip').val(rsp.d.ZipCode);
SetPerson(rsp.d.Age);
}

rsp.d 是一个包含所有属性的字符串...属性本身未定义。我知道我在这里缺少一些简单的东西。

从服务器返回的字符串

"Person": {"FirstName":"Psuedomatt","LastName":"Tally-cox","Address":"5035 Macleay Rd SE","City":"Salem","State":"Oregon","ZipCode":"97317","Age":99}

最佳答案

您不应该手动序列化返回值; ASP.NET 将为您做到这一点。尝试这样的事情:

[WebMethod]
public static Person GetPersonInfo(string pFirstName, string pLastName)
{
// Assuming you have a server-side Person class.
Person p = new Person();

p.FirstName = "Pseudo" + pFirstName;
p.LastName = "Tally-" + pLastName;
p.Address = "5035 Macleay Rd SE";
p.City = "Salem";
p.State = "Oregon";
p.ZipCode = "97317";

// ASP.NET will automatically JSON serialize this, if you call it with
// the correct client-side form (which you appear to be doing).
return p;
}

如果您需要返回更动态的内容,就像您的示例似乎所做的那样,您可以使用匿名类型:

[WebMethod]
public static object GetPersonInfo(string pFirstName, string pLastName)
{
// ASP.NET will automatically JSON serialize this as well.
return new {
FirstName = "Pseudo" + pFirstName,
LastName = "Tally-" + pLastName,
Address = "5035 Macleay Rd SE",
City = "Salem",
State = "Oregon",
ZipCode = "97317"
}
}

关于jquery - WebMethod 返回 JSON,但我的 $.ajax() 回调中的响应 obj 只是一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5228648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com