从 WebMethod 返回时,我很难正确处理对象。 条件(我之后的研究):
保存属性的简单类:
public class memberLogin
{
public string Username {get; set;}
public string Password {get; set;}
}
序列化方法:
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
(为了清晰起见,进行了简化)Webmethod
[WebMethod(EnableSession = true)]
public static string getCredentials()
{
memberLogin ml = new memberLogin();
ml.Username = "user";
ml.Password = "pass";
string json = JsonHelper.JsonSerializer<memberLogin>(ml);
return json;
}
return null;
}
和 JavaScript
$("#element").live("click", function (e) {
$.ajax({
type: "POST",
url: "Default.aspx/getCredentials",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: post_to_url
});
});
function post_to_url(params) {
method = "post";
path = "http://example";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
调试时,WebMethod 返回 "{\"Password\":\"pass\",\"Username\":\"user\"}"
所以这似乎是我想要的它是 (key, value par),除了 \
但这就是它的序列化方式。
但是,当使用 ajax 检索时,我无法从中获取任何值。 alert(params)
给出 object Object
,调用 params.Username 给出 undefined
。我有什么遗漏的吗?某种 Actor 阵容?
我认为如果对象被序列化,那么就没有这样的需要。
抱歉,帖子很长,但我尽力提供尽可能多的信息。
最佳答案
您必须将 JSON 字符串解析为 JSON 对象。 在 JavaScript 中:
var user = JSON.parse(params.responseText);
var username = user.Username;
var password = user.Password;
关于c# - WebMethod 返回 JSON 对象问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15096488/