Reputation: 36078
I am trying to pass a JSON object to .getJSON but I keep getting a bad request error. This is what I am trying:
var data = {
"SomeID": "18",
"Utc": null,
"Flags": "324"
};
$.getJSON("https://somewhere.com/AllGet?callback=?", JSON.stringify(data), function (result) {
alert(result);
});
Currently to get it working, I have to do this, but I do not like how I have to manually construct the query string:
$.getJSON("https://somewhere.com/AllGet?SomeID=18&Utc=&Flags=324&callback=?", null, function (result) {
alert(result);
});
Anyone know how to make requests easier with JSON objects being passed in? I would appreciate any help or advise.
Upvotes: 15
Views: 78258
Reputation: 469
I tried encoding the json and it worked.
Not sure how efficient or practical it is, sharing it just as a work around for above question.
$.getJSON("https://somewhere.com/AllGet?data="+encodeURI(JSON.stringify(data)), function (result) {
alert(result);
});
Upvotes: 0
Reputation: 3212
why exactly do you need a callback? (Ow wait, jsonp) I'd try the following first:
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function(result) {
alert(result);
});
somewhere in firebug and see if it returns what you expect. I'm not sure what a string as data does, but just giving an object works fine afaik.
Upvotes: 1
Reputation: 19217
You don't need to do JSON.stringfy
, just pass the JSON object, jQuery will construct your URL parameter with that
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) {
alert(result);
});
Upvotes: 1
Reputation: 31033
$.getJSON("https://somewhere.com/AllGet?callback=?", {SomeID:"18",Utc:null,Flags:"324"}, function (result) {
alert(result);
});
OR
var data = {
"SomeID": "18",
"Utc": null,
"Flags": "324"
};
$.getJSON("https://somewhere.com/AllGet?callback=?",
{
SomeID:data.SomeID,
Utc:data.Utc,
Flags:data.Flags
},
function (result) {
alert(result);
});
Upvotes: 0
Reputation: 3535
according to the site, this is valid:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
alert("JSON Data: " + json.users[3].name);
});
so try:
var data = {
SomeID: "18",
Utc: null,
Flags: "324"
};
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) {
alert(result);
});
edit: http://api.jquery.com/jQuery.getJSON/
Upvotes: 31
Reputation: 78850
When you provide data to a jQuery GET request, it expects an object, not a JSON string, for constructing the query string parameters. Try changing your original code to just this:
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) {
alert(result);
});
Upvotes: 3
Reputation: 13756
Dont use JSON.stringfy, just pass data as it is.
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) {
alert(result);
});
Upvotes: 3