jQuery/json 从 .NET Web 服务中的 POST 读取参数

标签 jquery web-services json parameters

我无法弄清楚如何从来自 jQuery 的 POST 中读取 json 字符串(我见过的大多数文章都展示了如何发送 json,但没有展示如何从网络收到的 POST 消息中获取它)服务。

这是我到目前为止编写的代码。

在客户端:

<input type="text" id="UserNameText" />
<br />
<input type="password" id="PasswordText" />
<br />
<input type="button" id="Login" value="Login" onclick="DoLogin();" />

<script type="text/javascript" language="javascript">
    function DoLogin() 
    {
        var un = document.getElementById('UserNameText').value;
        var pw = document.getElementById('PasswordText').value;
        var info = "{ 'UserName':'" + un + "', 'Password':'" + pw + "'}";

        $.ajax(
        {
            type: "POST",
            url: "http://localhost:60876/Login.asmx/LoginSpecial",
            dataType: 'json',
            data: info,
            contentType: "application/json; charset=utf-8",
            success: function (msg) { alert(msg.d); },
            error: function (msg) { alert(msg.responseText); }
        });
    }
</script>

在服务器端我有这个:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public string LoginSpecial()
{
    // none of these seem to be working
    NameValueCollection parameters = HttpContext.Current.Request.Params;
    string p = parameters["QUERY_STRING"] != null ? parameters["QUERY_STRING"].ToString() : String.Empty;
    string info = HttpContext.Current.Request["info"] != null ? HttpContext.Current.Request["info"].ToString() : String.Empty;
    string data = HttpContext.Current.Request["data"] != null ? HttpContext.Current.Request["data"].ToString() : String.Empty;

    // test json string, need to read from the jquery post
    string json = "{ 'UserName':'test', 'Password':'test'}";

    // the following two lines of code work ok with the test json string above.
    JavaScriptSerializer serial = new JavaScriptSerializer();
    Credentials credential = (Credentials)serial.Deserialize(json, typeof(Credentials));

    return "Some json message here";
}

我已经设置了断点,并且按预期访问了 Web 服务,我只是不知道如何从 POST 消息中获取 json 字符串。

最佳答案

如果您希望 Web 服务方法能够处理提交的 JSON 对象,则必须将方法签名更改为:

[WebMethod]
LoginSpecial(string Username, string Password)
{
}

您提供给 AJAX 调用的 data 属性的 JSON 对象必须具有与 Web 服务方法签名的参数名称相匹配的属性名称。

如果要提交参数列表,则必须提交对象数组并在 Web 服务中创建包装器 .NET 对象,如下所述:

Using jQuery to POST Form Data to an ASP.NET ASMX AJAX Web Service

希望有帮助。

关于jQuery/json 从 .NET Web 服务中的 POST 读取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4692334/

相关文章:

javascript - DOM 加载后,Jquery 函数无法与多个函数一起使用

web-services - DAO 微服务是微服务架构中的好方法吗?

web-services - 世界时钟网络服务?

javascript - jQuery 延迟直到背景图像加载,然后淡入?

jquery - 下拉框出现在屏幕外

php - jquery 验证成功后,页面不会重定向到特定位置

javascript - 使用 jquery 调用 webservice 时出错

ios - UITableView带有Json文件,加载图像到单元格消失

java - 尝试获取字符串是否有作者、标题、出版商等

javascript - d3.js 从 url 获取 JSON