从 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\"}"
,所以它似乎是我想要的(键,值 par),\
但它是如何序列化的。但是,当使用 ajax 检索时,我无法从中获取任何值。alert(params)
给object Object
, 调用 params.Username 给undefined
. 有什么我想念的吗?某种演员?我认为如果对象被序列化,那么就没有这样的需要。很抱歉发了很长的帖子,但我试图提供尽可能多的信息。