在jQuery中将JSON数据传递给.getJSON?
我试图将JSON对象传递给.getJSON,但我一直收到错误的请求错误。 这就是我想要的:
var data = { "SomeID": "18", "Utc": null, "Flags": "324" }; $.getJSON("https://somewhere.com/AllGet?callback=?", JSON.stringify(data), function (result) { alert(result); });
目前为了使它工作,我必须这样做,但我不喜欢我必须手动构建查询字符串:
$.getJSON("https://somewhere.com/AllGet?SomeID=18&Utc=&Flags=324&callback=?", null, function (result) { alert(result); });
任何人都知道如何通过传入JSON对象来简化请求? 我将不胜感激任何帮助或建议。
根据网站,这是有效的:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) { alert("JSON Data: " + json.users[3].name); });
所以尝试:
var data = { SomeID: "18", Utc: null, Flags: "324" }; $.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) { alert(result); });
编辑: http : //api.jquery.com/jQuery.getJSON/
不要使用JSON.stringfy,只是按原样传递数据。
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) { alert(result); });
当您向jQuery GET请求提供数据时,它需要一个对象而不是JSON字符串来构造查询字符串参数。 尝试将原始代码更改为:
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) { alert(result); });
你不需要做JSON.stringfy
,只需传递JSON对象,jQuery就会用它构造你的URL参数
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) { alert(result); });
为什么你需要回调? (Ow等,jsonp)我先尝试以下方法:
$.getJSON("https://somewhere.com/AllGet?callback=?", data, function(result) { alert(result); });
在firebug的某个地方,看看它是否会返回你所期望的。 我不确定数据字符串是什么,但只是给对象一个正常的工作。
$.getJSON("https://somewhere.com/AllGet?callback=?", {SomeID:"18",Utc:null,Flags:"324"}, function (result) { alert(result); });
要么
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); });
我尝试编码json并且它有效。
不确定它是多么有效或实用,分享它只是为了解决上述问题。
$.getJSON("https://somewhere.com/AllGet?data="+encodeURI(JSON.stringify(data)), function (result) { alert(result); });