Reputation: 19939
I am posting to a rails controller an array of json objects via a jQuery ajax request. Do I need to use JSON.stringify or should jQuery handle it for me?
var vals = [{"name":"item name #1"},{"name":"item name #2"}];
$.ajax({
url: '/arc/api/v1/calculate_items',
type: 'POST',
data: {line_items: vals},
dataType: 'json'
}).done(function(r){
vs
var vals = [{"name":"item name #1"},{"name":"item name #2"}];
$.ajax({
url: '/arc/api/v1/calculate_items',
type: 'POST',
data: {line_items: JSON.stringify(vals)},
dataType: 'json'
}).done(function(r){
Upvotes: 1
Views: 59
Reputation: 44360
Do I need to use JSON.stringify?
You need to use JSON.stringify
to first serialize
your object(or an array of objects) to JSON, and then specify the content-type so your server understands it's JSON.
jQuery handle it for me?
No, it is not.
There are two jQuery method which does it automaticly, getJSON
, post
$.getJSON("/some/url", function(data) {
// the data is already a plain JSON object
})
var data = /* Your data in JSON format - see below */;
$.post("/some/url", data, function(returnedData) {
// the returnedData is already a plain JSON object
})
Upvotes: 1