WebMethod返回JSON对象问题

本文关键字:问题 对象 JSON 返回 WebMethod | 更新日期: 2023-09-27 18:01:19

当从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,调用参数。用户名给出undefined。我是不是漏掉了什么?某种石膏?我认为如果对象是序列化的,那么就没有这个必要了。

WebMethod返回JSON对象问题

您必须将JSON String解析为JSON对象。在Javascript中:

var user = JSON.parse(params.responseText);
var username = user.Username;
var password = user.Password;