gpt4 book ai didi

jquery - 如何从 2.0 asmx Web 服务返回 JSON

转载 作者:行者123 更新时间:2023-12-03 21:34:28 26 4
gpt4 key购买 nike

我正在使用 .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);
}
});
});

以下是 Fiddler 中的请求 header :

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”并得到相同的结果。

这是网络服务方法:

<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>

有谁知道当我请求 Json 时如何强制 Web 服务返回 Json?

请不要告诉我升级到 .Net Framework 3.5 或类似的东西(我没那么傻)。我需要一个 2.0 解决方案。

最佳答案

return JSON from ASMX services in ASP.NET 2.0没问题。您只需要安装 ASP.NET AJAX 扩展即可。

请务必将 [ScriptService] 装饰添加到您的 Web 服务中。这就是指示 ASP.NET AJAX 框架的服务器端部分为正确形成的请求返回 JSON 的内容。

此外,如果您在 2.0 中使用它,则需要在我的示例中从“msg.d”中删除“.d”。 The ".d" is a security feature that came with 3.5 .

关于jquery - 如何从 2.0 asmx Web 服务返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/288850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com