我无法弄清楚如何从来自 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/