Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...