将JSON数据传递到jQuery中的.getJSON
Passing JSON data to .getJSON in jQuery?
我试图将一个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);
});
为什么需要回调?(哦,等等,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);
});
相关文章:
- jquery中的文本框验证
- 是否可以禁用jquery中的单个单选按钮
- 禁用jQuery中的下拉列表
- Javascript/jQuery中的并行Ajax调用
- 如何从javascript/jquery中的复选框中获取布尔值
- JQuery中的活动搜索栏
- jquery中的复选框依赖项
- 正在停止.在jquery中的特定时间间隔内,每次迭代的每次执行
- 将值动态绑定到jquery中的切换按钮
- 如何使jQuery中的悬停函数单独应用于数据库映像
- jQuery中的attr()是否强制小写
- position 是 JavaScript 或 jQuery 中的一个数组
- 存储JQuery中的选项值
- 如何在JQuery中的.html()方法中包含fadeneffect
- 比较jquery中的两个输入
- jQuery中的状态管理是什么
- 如何从javascript/jquery中的多个复选框中获取附加值
- jquery中的PHP代码不起作用
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 当所有输入文本字段都为空时,禁止表单提交,但当jquery中的任何字段不为空时允许提交