始终在 jQuery Ajax 的发布数据上调用 JSON.stringify

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

Always call JSON.stringify on post data for jQuery Ajax

jqueryajax

提问by Dirk Boer

Or any other function to preprocess your data for that matter :)

或任何其他功能来预处理您的数据:)

Because of my server side framework, I always need to call JSON.stringify before sending my data - unnecessary boilerplate, that you can forget to add.

由于我的服务器端框架,我总是需要在发送我的数据之前调用 JSON.stringify - 不必要的样板,您可以忘记添加。

Right now I have:

现在我有:

$.ajax({
    [...]
    data: JSON.stringify({ someData: self.someData }),
    [...]
});

I would prefer:

我会选择:

$.ajax({
    [...]
    data: { someData: self.someData },
    [...]
});

I've looked into ajaxSetup, but can't find a solution for this, so far...

我已经研究了ajaxSetup,但到目前为止找不到解决方案......

Update

更新

For a reason why I need this, see the following this question. I could fix this on the serverside, but for now I'm looking for a way to fix this on the clientside.

出于我需要这个的原因,请参阅以下这个问题。我可以在服务器端解决这个问题,但现在我正在寻找一种在客户端解决这个问题的方法。

回答by Kevin B

No, there is no built-in way to pre-process your data from an object to JSON. However, you can use ajaxSetupand a beforeSendto do it for you.

不,没有将数据从对象预处理为 JSON 的内置方法。但是,您可以使用ajaxSetup和 abeforeSend来为您完成。

$.ajaxSetup({
    beforeSend: function(jqXHR,options){
        if ( options.contentType == "application/json" && typeof options.data != "string" ) {
            options.data = JSON.stringify(options.data);
        }
    }
});

Now just make sure to set your contentTypeto application/jsonon requests that need to send json to the server so that it will get caught by the if statement.

现在只需确保将您设置contentTypeapplication/jsonon 需要将 json 发送到服务器的请求,以便它会被 if 语句捕获。

回答by nathanallen

Here an alternative approach that uses a jQuery.prefilter:

这是使用jQuery.prefilter的替代方法:

$.ajaxPrefilter("json", function(options, originalOptions) {
  options.data = JSON.stringify(originalOptions.data || null);
  options.contentType = "application/json" // content type of *request*
});

$.ajax({
  data: {foo: [1,2,3]},
  dataType: "json" // expected content type of *response* (must match prefilter, above!)
  [...]
});

Because prefilters match on the dataTypeoption, we have to set it manually in our $.ajaxrequest. If the dataTypematches the prefilter ("json") then before the request is sent, it will convert the dataobject to a string, and set the contentTypeheader to match ("application/json").

因为预过滤器匹配dataType选项,我们必须在我们的$.ajax请求中手动设置它。如果dataType匹配预过滤器(“json”),则在发送请求之前,它将data对象转换为字符串,并将contentType标头设置为匹配(“application/json”)。

Keep in mind that this a a globalchange that will impact ALL future $.ajaxrequests with dataType: "json"!

请记住,此全局更改将影响所有未来的$.ajax请求dataType: "json"

回答by Chtiwi Malek

Here's the jQuery.prefilterfunction i use (it's better than the beforeSend approach), it will match any datatype, and will serialize any object in a post or put request.

这是我使用的jQuery.prefilter函数(它比 beforeSend 方法更好),它将匹配任何数据类型,并将序列化 post 或 put 请求中的任何对象。

$.ajaxPrefilter(function (options, org) {
    var rtype = options.type.toLowerCase();
    if ((rtype === "post" || rtype === "put") && org.data !== null && typeof org.data === 'object') {
        options.data = JSON.stringify(org.data);
    }
});

hope this helps.

希望这可以帮助。

回答by user2505659

User Jquery.getJSON().You can directly get json data.

用户Jquery.getJSON().可以直接获取json数据。

$.getJSON('', function(data) {

//you can use data.
});

http://api.jquery.com/jQuery.getJSON/

http://api.jquery.com/jQuery.getJSON/