親愛的未來的讀者:目前公認的答案是不正確的方式。它使你使用JavaScriptSerializer
,並且你失去了請求xml的能力(或者確實會有將來出現的任何序列化格式)。 「正確的方式」也涉及較少的代碼!
如果你裝飾用[ScriptService]
屬性服務類 - 你有 - 然後ASP.NET 3.5 +會自動序列化到JSON響應提供您Ajax調用請求JSON。除非您希望使用不同的序列化程序,例如Newtonsoft,否則手動連續化到JSON的建議是錯誤的。
,你是看到XML提出以下建議之一:
- 你是不是在你的Ajax調用請求JSON - 請在下面的工作
- 示例代碼可能是一些web.config中的條目丟失,根據到一個答案 here(免責聲明:我沒有這些在生產 網絡中的大部分。配置;纔開始與這些玩,如果沒有其他作品)
這裏是一個JSON的一個簡單的工作示例啓用ASMX Web服務:
<%@ WebService Language="C#" Class="WebService" %>
using System;
using System.Collections.Generic;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
[WebMethod]
public MyClass Example()
{
return new MyClass();
}
public class MyClass
{
public string Message { get { return "Hi"; } }
public int Number { get { return 123; } }
public List<string> List { get { return new List<string> { "Item1", "Item2", "Item3" }; } }
}
}
JavaScript來要求它,並處理響應(我們將簡單地彈出一個JS警報從MyClass.Message消息):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "WebService.asmx/Example",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{ }",
error: function (XMLHttpRequest, textStatus, errorThrown) { alert(langError + " " + textStatus); },
success: function (msg) {
alert(msg.d.Message);
}
});
</script>
</body>
</html>
HTTP請求:
POST http://HOST.com/WebService.asmx/Example HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://HOST.com/Test.aspx
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Connection: Keep-Alive
Content-Length: 3
Host: HOST.com
{ }
HTTP響應:
HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 20 Feb 2018 08:36:12 GMT
Content-Length: 98
{"d":{"__type":"WebService+MyClass","Message":"Hi","Number":123,"List":["Item1","Item2","Item3"]}}
結果:
「您好」 被顯示在一個彈出JS。
可能的重複[使用jQuery從.NET服務獲取JSON數據:與ajax設置混淆](http://stackoverflow.com/questions/5690882/get-json-data-with-jquery-from-a- net-service-confused-with-ajax-setup) – GSerg
[Asmx web服務如何返回JSON而不是XML?]的可能重複(https://stackoverflow.com/questions/14950578/asmx-web-service-how-回到json-and-not-xml) –