Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

javascript - Setting the POST-body to a JSON object with jQuery

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.

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 not what I'm after.

My 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

post "/api/user/create" do
    js = JSON.parse(request.body.read)
    # do something with the js object… this works when POSTing from Cocoa
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...