jQuery 如何从 2.0 asmx Web 服务返回 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/288850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return JSON from a 2.0 asmx web service
提问by camainc
I am using .Net framework 2.0 / jQuery to make an Ajax call to a 2.0 web service. No matter what I set the contentType to in the ajax call, the service always returns XML. I want it to return Json!
我正在使用 .Net 框架 2.0/jQuery 对 2.0 Web 服务进行 Ajax 调用。无论我在 ajax 调用中将 contentType 设置为什么,服务始终返回 XML。我想让它返回 Json!
Here is the call:
这是电话:
$(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);
}
});
});
Here is what the request header looks like in Fiddler:
这是 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
I have tried setting the contentType to 'text/json' and get the same results.
我尝试将 contentType 设置为 'text/json' 并获得相同的结果。
Here is the web service method:
这是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
and here is what it returns:
这是它返回的内容:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://DMS.Webservices.org/">{"DateTime":"11/13/2008 6:04:22 PM"}</string>
Does anyone know how to force the web service to return Json when I ask for Json?
有谁知道当我要求 Json 时如何强制 Web 服务返回 Json?
Please don't tell me to upgrade to .Net Framework 3.5 or anything like that (I'm not that stupid). I need a 2.0 solution.
请不要告诉我升级到 .Net Framework 3.5 或类似的东西(我没那么蠢)。我需要一个 2.0 解决方案。
回答by Dave Ward
It's no problem to return JSON from ASMX services in ASP.NET 2.0. You just need the ASP.NET AJAX Extensions installed.
在 ASP.NET 2.0 中从 ASMX 服务返回 JSON没有问题。您只需要安装 ASP.NET AJAX 扩展。
Do be sure to add the [ScriptService] decoration to your web service. That's what instructs the server side portion of the ASP.NET AJAX framework to return JSON for a properly formed request.
请务必将 [ScriptService] 装饰添加到您的 Web 服务中。这就是指示 ASP.NET AJAX 框架的服务器端部分为正确格式的请求返回 JSON 的原因。
Also, you'll need to drop the ".d" from "msg.d" in my example, if you're using it with 2.0. The ".d" is a security feature that came with 3.5.
此外,如果您在 2.0 中使用它,则在我的示例中,您需要从“msg.d”中删除“.d”。 “.d”是 3.5 附带的安全功能。
回答by Tom
The response is wrapped in a element because you're method says it will return a string. You could use this to be able to send plain json, but your wsdl will be fooled (the function is void but does respond data).
响应包含在一个元素中,因为您的方法说它将返回一个字符串。您可以使用它来发送纯 json,但是您的 wsdl 会被愚弄(该函数无效但确实响应数据)。
[WebMethod(Description="return pure JSON")]
public void retrieveByIdToPureJSON( int id )
{
Context.Response.Write( JsonConvert.SerializeObject( mydbtable.getById(id) );
}
Good luck, tom
祝你好运,汤姆
Btw: see Newtonsoft.Json for JsonConvert
顺便说一句:JsonConvert 见 Newtonsoft.Json
回答by Darko Z
You need to decorate your web method with the following:
您需要使用以下内容装饰您的网络方法:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
You've got the rest right :)
More info at Encosiaand Andrew Roland's Blog
剩下的就对了 :)
更多信息请访问Encosia和Andrew Roland 的博客
EDIT: As noted below this is .NET 3.5 only (I was unaware of this, my bad).
编辑:如下所述,这只是 .NET 3.5(我不知道这一点,我的错)。
回答by redsquare
You can use the Jayrock libraryQuick start for asp.net
This allows you to write a http handler to return you json.
这允许您编写一个 http 处理程序来返回您的 json。
<%@ WebHandler Class="JayrockWeb.HelloWorld" %>
namespace JayrockWeb
{
using System;
using System.Web;
using Jayrock.Json;
using Jayrock.JsonRpc;
using Jayrock.JsonRpc.Web;
public class HelloWorld : JsonRpcHandler
{
[ JsonRpcMethod("greetings") ]
public string Greetings()
{
return "Welcome to Jayrock!";
}
}
}
回答by Mark Cidade
You probably can't do anything other than XML or binary serialization in .NET 2.0. If you're not using an autogenerated web reference then don't bother with ASMX. Just use an ASPX or ASHX instead.
在 .NET 2.0 中,除了 XML 或二进制序列化之外,您可能无法执行任何操作。如果您没有使用自动生成的 Web 参考,那么请不要使用 ASMX。只需使用 ASPX 或 ASHX。
回答by Seth
It's also possible to just write up your own quick JSON converter using Refelction.
也可以使用 Refelction 编写自己的快速 JSON 转换器。
Dim sb As New StringBuilder("{")
For Each p As PropertyInfo In myObject.GetType().GetProperties()
sb.Append(String.Format("""{0}"":""{1}"",", p.Name, p.GetValue(myObject,
Nothing).ToString()))
Next p
//remove the last "," because it's uneeded.
sb.Remove(sb.Length - 1, 1)
sb.Append("}")
回答by Jon P
I may not be 100% correct on this but I'm sure .net webservices are XML/SOAP based.
我可能不是 100% 正确,但我确信 .net webservices 是基于 XML/SOAP 的。
You would need to override the default behavior of the webservice. I'm not entirely sure that this would even be possible.
您需要覆盖网络服务的默认行为。我不完全确定这甚至是可能的。
I know this won't be the most useful answer, but may get you headed in the right direction.
我知道这不是最有用的答案,但可能会让您朝着正确的方向前进。