我使用.Net框架2.0 / jQuery做一个Ajax调用2.0 Web服务。不管我在ajax调用中设置了contentType,服务总是返回XML。我想让它返回Json!
这里是电话:
$(document).ready(function() { $.ajax({ type: "POST",url: "DonationsService.asmx/GetDate",data: "{}",contentType: "application/json; charset=utf-8",dataType: "json",success: function(msg) { // Hide the fake progress indicator graphic. $('#RSSContent').removeClass('loading'); // Insert the returned HTML into the <div>. $('#RSSContent').html(msg.d); } }); });
这里是请求标头在Fiddler中的样子:
POST /DonationsService.asmx/GetDate HTTP/1.1 x-requested-with: XMLHttpRequest Accept-Language: en-us Referer: http://localhost:1238/text.htm Accept: application/json,text/javascript,*/* Content-Type: application/json; charset=utf-8 Accept-Encoding: gzip,deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; eMusic DLM/4; .NET CLR 2.0.50727) Host: localhost:1238 Content-Length: 2 Connection: Keep-Alive Pragma: no-cache
我已经尝试将contentType设置为“text / json”并获得相同的结果。
这里是web服务方法:
<WebMethod()> _ Public Function GetDate() As String 'just playing around with Newtonsoft.Json Dim sb As New StringBuilder Dim sw As New IO.StringWriter(sb) Dim strOut As String = String.Empty Using jw As New JsonTextWriter(sw) With jw .WriteStartObject() .WritePropertyName("DateTime") .WriteValue(DateTime.Now.ToString) .WriteEndObject() End With strOut = sw.ToString End Using Return strOut End Function
这里是它返回:
<?xml version="1.0" encoding="utf-8"?> <string xmlns="http://DMS.Webservices.org/">{"DateTime":"11/13/2008 6:04:22 PM"}</string>
有人知道如何强制Web服务返回Json时,我问Json?
解决方法
这对
return JSON from ASMX services in ASP.NET 2.0没有问题。你只需要安装ASP.NET AJAX扩展。
确保将[ScriptService]装饰添加到您的Web服务。这就是指示ASP.NET AJAX框架的服务器端部分为正确形成的请求返回JSON。
此外,如果你在2.0中使用它,你需要在我的例子中删除“.d”。 The “.d” is a security feature that came with 3.5。