我很難搞清楚如何從jQuery的POST中讀取json字符串(我見過的大多數文章展示瞭如何發送json,但不是如何從Web服務接收到請求消息得到它jQuery/json從.NET的Web服務中讀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字符串。
我試過:公共字符串LoginSpecial(字符串參數) 現在當我調用web服務我得到以下錯誤:無效的Web服務調用,參數缺失值:\ u0027parameter \ u0027。「,」StackTrace「:」.... – 2011-01-14 15:08:35