jQuery 如果 ContentType 不是 JSON,我可以从 .asmx Web 服务返回 JSON 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2670147/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:00:06  来源:igfitidea点击:

Can I return JSON from an .asmx Web Service if the ContentType is not JSON?

jqueryweb-servicesjsonresponse.contenttype

提问by Click Ahead

I would like to post a form using ajax and jquery to a .asmx webservice and return the value from the webservice as JSON.

我想将使用 ajax 和 jquery 的表单发布到 .asmx webservice,并将 webservice 的值作为 JSON 返回。

I'm using ASP.NET 4.0. I know that in order to return JSON from a webservice the following needs to be set (1) dataType: "json" (2) contentType: "application/json; charset=utf-8", (3) type: "POST" (4) set the Data to something. I have tested this and it works fine (i.e. my webservice returns the data as JSON) if all **fourare set**.

我正在使用 ASP.NET 4.0。我知道为了从网络服务返回 JSON,需要设置以下内容 (1) dataType: "json" (2) contentType: "application/json; charset=utf-8", (3) type: "POST" (4) 将数据设置为某物。我已经对此进行了测试,如果设置了所有 **四个** ,它就可以正常工作(即我的 web 服务将数据作为 JSON 返回)。

But, lets say in my case I want to do a standard form post i.e. test1=value1&test2=value2 so the contentType is not JSON but I want back JSON {test1:value1}. This doesn't seem to work because the contentType is "application/x-www-form-urlencoded" not "application/json; charset=utf-8".

但是,假设在我的情况下,我想做一个标准的表单发布,即 test1=value1&test2=value2 所以 contentType 不是 JSON 但我想要返回 JSON {test1:value1}。这似乎不起作用,因为 contentType 是“ application/x-www-form-urlencoded”而不是“ application/json; charset=utf-8”。

Can anyone tell me why I can't do this? It seems crazy to me that you have to explicitly send JSON to get JSON back, yet if you don't use JSON (i.e. post urlencoded contenttype) then the webservice will return XML.

谁能告诉我为什么我不能这样做?对我来说,您必须显式发送 JSON 才能返回 JSON,这似乎很疯狂,但是如果您不使用 JSON(即 post urlencoded contenttype),那么网络服务将返回 XML。

Any insights are greatly appreciated :)

非常感谢任何见解:)

回答by Oleg

If you will use WFC RESTfull Service instead of .asmx webservice you can implement all your requirements from your question. But usage of .asmx webservice with JSON as output requiredthat you use at least contentType: 'application/json'. In different places you can find as a reason - security reason (see JSON HiHymaning).

如果您将使用 WFC RESTfull 服务而不是 .asmx webservice,您可以根据您的问题实现您的所有要求。但是使用 .asmx 网络服务和 JSON 作为输出要求您至少使用contentType: 'application/json'. 在不同的地方你可以找到一个原因——安全原因(参见 JSON HiHymaning)。

Probably 'x-www-form-urlencoded' is not your real problem. If you use dataType: "json"the parameters will be also send in the form "test1=value1&test2=value2"!!! The only difference, that all values should be JSON encoded. And jQuery don't makes JSON encoding of the data. (You can look in the code of jQuery.) The main difference is only that "Accept: application/json" will be explicitly set in the request header.

可能 'x-www-form-urlencoded' 不是你真正的问题。如果使用dataType: "json"参数也会以“test1=value1&test2=value2”的形式发送!!!唯一的区别是所有值都应该是 JSON 编码的。并且 jQuery不会对数据进行 JSON 编码。(你可以查看 jQuery 的代码。)主要区别只是“Accept: application/json”会在请求头中显式设置。

Look at JQuery ajax call to httpget webmethod (c#) not workingwhich I wrote recently. In this post was asked example of GET request. But it is almost the same. The only difference is, that dataafter encoding will be appended to the URL (for GET request). For POST request the datawill be send in body. By the way if one set "processData: false" (see http://api.jquery.com/jQuery.ajax/) the GET data will be also send inside of body. So read my code example from JQuery ajax call to httpget webmethod (c#) not working. I hope you receive ideas how you can implement what you will.

看看我最近写的对 httpget webmethod (c#) 的 JQuery ajax 调用不起作用。在这篇文章中被问到 GET 请求的例子。但它几乎是一样的。唯一的区别是,编码后的数据将附加到 URL(对于 GET 请求)。对于 POST 请求,数据将在正文中发送。顺便说一下,如果设置了“processData: false”(参见http://api.jquery.com/jQuery.ajax/),GET数据也将在正文中发送。所以从JQuery ajax call to httpget webmethod (c#) not working阅读我的代码示例。我希望你能得到想法,如何实现你想要的。

I think you had problems with encoding complex data for your .asmx webservice call. Here is example with "complex" data:

我认为您在为 .asmx 网络服务调用编码复杂数据时遇到了问题。以下是“复杂”数据的示例:

[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public OutputData AjaxGetMore (InputData input) {
    return new OutputData () {
        id = input.id,
        message = new List { "it's work!", "OK!" },
        myInt = new int[] { input.myInt[0] + 1, input.myInt[1] + 1, 20, 75 },
        myComplexData = new InternalData () { blaBla = "haha", iii = new int[] { 1, 2, 3, 4, 5 } }
    };
}

where

在哪里

public class InternalData {
    public string blaBla { get; set; }
    public int[] iii { get; set; }
}
public class OutputData {
    public string id { get; set; }
    public List message { get; set; }
    public int[] myInt { get; set; }
    public InternalData myComplexData { get; set; }
}
public class InputData {
    public string id { get; set; }
    public int[] myInt { get; set; }
    public InternalData data { get; set; }
}

and on the client side

在客户端

var myData = { id: "li1234", myInt: [100, 200], data : {blaBla: "Hahhh!", iii: [10,20,30]}}
var myDataForjQuery = {input:$.toJSON(myData)};
$.ajax({
    type: "GET",
    url: "/Service1.asmx/AjaxGetMore", // + idAsJson,
    data: myDataForjQuery, // idAsJson, //myData,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(msg) {
        // var msg = {__type: "Testportal.outputData", id: "li1234", message: "it's work!", myInt:101}
        alert("message=" + msg.d.message + ", id=" + msg.d.id + ", myInt=" + msg.d.myInt); 
    },
    error: function(res, status) {
        if (status ==="error") {
            // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
            var errorMessage = $.parseJSON(res.responseText);
            alert(errorMessage.Message);
        }
    }
});

($.toJSONcome from the JSON plugin ) You can modify this example to HTTP POST, if you want.

$.toJSON来自 JSON 插件)如果需要,您可以将此示例修改为 HTTP POST。

One more small advice. If you use jQuery 1.4.x you can try use 'none' as dataType. See documentation: "If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string)"

还有一个小建议。如果您使用 jQuery 1.4.x,您可以尝试使用 'none' 作为 dataType。请参阅文档:“如果没有指定,jQuery 将根据响应的 MIME 类型智能地尝试获取结果(XML MIME 类型将产生 XML,在 1.4 JSON 将产生一个 JavaScript 对象,在 1.4 脚本将执行脚本,其他任何内容都将作为字符串返回)”

Best regards

此致

回答by jAndy

Request and response headers are different storys. Thus, it's not necessary to send a specific datatype in order to receive it.

请求和响应头是不同的故事。因此,没有必要发送特定的数据类型来接收它。

In the case of jQuery, just use the underlaying .ajax()function with dataType set to 'json'. The rest depends on your calling script/service.

在 jQuery 的情况下,只需使用.ajax()dataType 设置为 'json'的底层函数。其余的取决于您的调用脚本/服务。

回答by Taylor Leese

You should also set the contentType in the JSON request as well. This will ensure you don't have application/x-www-form-urlencoded in the request. Instead, it will give you want you want: application/json; charset=utf-8.

您还应该在 JSON 请求中设置 contentType。这将确保您在请求中没有 application/x-www-form-urlencoded。相反,它会给你想要的:application/json; 字符集=utf-8。

$.ajax({
    url: '/your/site',
    contentType: 'application/json',
    dataType: 'json',
    data: jsonString,
    type: 'post',
    success: function (data) {
        /* do stuff */
    }
});