Javascript 使用 jQuery 将 POST-body 设置为 JSON 对象

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

Setting the POST-body to a JSON object with jQuery

javascriptjqueryjson

提问by jbrennan

I'm trying to write a JSON-based web API in a Sinatra app. I want to POST a JSON object as the post body (with the proper content-type set) but I'm struggling.

我正在尝试在 Sinatra 应用程序中编写基于 JSON 的 Web API。我想发布一个 JSON 对象作为帖子正文(使用正确的内容类型集),但我很挣扎。

In Cocoa, I'd do something like

在可可中,我会做类似的事情

[mutableHTTPRequest setHTTPBody:dataRepresentationOfJSONObject];

And the content type, set to JSON, would then post the HTTP body as a JSON object. I'm trying to do this with jquery. The best I can do so far just takes the JSON object and turns it into a normal style key=value&…style post body, and that's notwhat I'm after.

然后内容类型设置为 JSON,然后将 HTTP 正文作为 JSON 对象发布。我正在尝试用 jquery 来做到这一点。到目前为止,我能做的最好的事情就是将 JSON 对象转换为普通key=value&…样式的帖子正文,这不是我所追求的。

My Javascript:

我的Javascript:

var data = { "user" : "me!" };
$.ajax({
    type: "POST",
    url: "/api/user/create",
    contentType: 'application/json',
    data: data,
    success: function(r) {

});

Any pointers on how to do this? My goal is for my Sinatra to do like the following

有关如何执行此操作的任何指示?我的目标是让我的 Sinatra 做到以下几点

post "/api/user/create" do
    js = JSON.parse(request.body.read)
    # do something with the js object… this works when POSTing from Cocoa
end

回答by Kevin B

Add the processData parameter to your ajax request and set it to false. Additionally, you need to stringify your object to turn it into JSON.

将 processData 参数添加到您的 ajax 请求并将其设置为 false。此外,您需要对对象进行字符串化以将其转换为 JSON。

var data = { "user" : "me!" };
$.ajax({
    type: "POST",
    url: "/api/user/create",
    processData: false,
    contentType: 'application/json',
    data: JSON.stringify(data),
    success: function(r) {
    }
});

JSON.stringifywill not work in older versions of IE unless you implement it. http://json.org

JSON.stringify除非您实现它,否则将无法在旧版本的 IE 中工作。http://json.org