cam*_*inc 27 .net asp.net ajax jquery web-services
我正在使用.Net framework 2.0/jQuery来对2.0 Web服务进行Ajax调用.无论我在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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
以下是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
Run Code Online (Sandbox Code Playgroud)
我已经尝试将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
Run Code Online (Sandbox Code Playgroud)
这是它的回报:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://DMS.Webservices.org/">{"DateTime":"11/13/2008 6:04:22 PM"}</string>
Run Code Online (Sandbox Code Playgroud)
当我要求Json时,有谁知道如何强制Web服务返回Json?
请不要告诉我升级到.Net Framework 3.5或类似的东西(我不是那么愚蠢).我需要2.0解决方案.
Dav*_*ard 35
从ASP.NET 2.0中的ASMX服务返回JSON没有问题.您只需要安装ASP.NET AJAX Extensions.
务必将[ScriptService]装饰添加到Web服务中.这就是指示ASP.NET AJAX框架的服务器端部分为正确形成的请求返回JSON的内容.
另外,如果你在2.0中使用它,你需要在我的例子中从"msg.d"中删除".d". ".d"是3.5附带的安全功能.
小智 12
响应包含在一个元素中,因为你的方法说它会返回一个字符串.你可以使用它来发送普通的json,但是你的wsdl会被愚弄(函数是无效但确实响应数据).
[WebMethod(Description="return pure JSON")]
public void retrieveByIdToPureJSON( int id )
{
Context.Response.Write( JsonConvert.SerializeObject( mydbtable.getById(id) );
}
Run Code Online (Sandbox Code Playgroud)
祝你好运,汤姆
顺便说一句:请参阅Newtonoft.Json获取JsonConvert
Dar*_*o Z 10
您需要使用以下内容装饰Web方法:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Run Code Online (Sandbox Code Playgroud)
你有其余的权利:)
更多信息在Encosia和Andrew Roland的博客
编辑:如下所述,这只是.NET 3.5(我没有意识到这一点,我的不好).
归档时间: |
|
查看次数: |
68404 次 |
最近记录: |