jQuery - 如何通过 Ajax 放置 JSON?

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

jQuery - How to PUT JSON via Ajax?

jqueryajaxjson

提问by Juri Glass

I am trying to put some JSON formatted data via Ajax with jQueryto a server. My code looks like this:

我试图通过带有jQuery 的Ajax 将一些 JSON 格式的数据放入服务器。我的代码如下所示:

$.ajax({
    type: "PUT",
    url: myURL,
    contentType: "application/json",
    data: {"data": "mydata"}
});

But on the server-side, I receive a data=mydatastring, instead of the expected JSON. Firebugtells me the same.

但是在服务器端,我收到一个data=mydata字符串,而不是预期的 JSON。Firebug告诉我同样的情况。

Where is the error?

错误在哪里?

采纳答案by Andy

I think the data needs to be a String. Objects are converted to query strings which is what you are seeing here.

我认为数据需要是一个字符串。对象被转换为查询字符串,这就是您在此处看到的内容。

You can use the JSON.stringify(obj)method to convert your Object to a String. The code for the JSON object is available from: https://github.com/douglascrockford/JSON-js/blob/master/json2.js.

您可以使用该JSON.stringify(obj)方法将对象转换为字符串。JSON 对象的代码可从:https: //github.com/douglascrockford/JSON-js/blob/master/json2.js 获得

Alternately, just pass the code you are using to create the object as a literal String, but I imagine this is just an example and you'll want to encode some object you've already created.

或者,只需将用于创建对象的代码作为文字字符串传递,但我想这只是一个示例,您需要对已创建的对象进行编码。

回答by Dmytro

If you always have to send JSON in your application, then you can just execute this somewhere in your init and then use default $.ajaxcall as in your example, and it will always serialize as a JSON string instead of the Ajax default query string.

如果你总是需要在你的应用程序中发送 JSON,那么你可以在你的 init 中的某个地方执行它,然后$.ajax像你的例子一样使用默认调用,它总是会序列化为 JSON 字符串而不是 Ajax 默认查询字符串。

Here I use the JSON object mentioned above:

这里我使用了上面提到的 JSON 对象:

$.ajaxSetup({
    contentType : 'application/json',
    processData : false
});
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
    if (options.data){
        options.data=JSON.stringify(options.data);
    }
});

回答by Neha

//url: this is a reference to the XML, where you need to define the mapping.
//<entry key="/getEmpDetails/transEfileGenerate.app">
//<bean class="com.adp.ems.framework.spring.MappingItem" p:delegate-ref="efilePageDelegate"
//p:action="passJSONObjectAndGetWebServiceOutput" />

//str1 is the input JSON that you need to pass... Ajax will automatically take care to get the response.
//</entry>

var kw = {
    url : "getEmpDetails/transEfileGenerate.app",
    timeout : 30000,
    handleAs : "json",
    sync: false,
    putData : str1,
    headers: { "Content-Type": "application/json"},
    load : function(result) {
},