2011-11-22 44 views
8

我想通过一个JSON对象.getJSON,但我不断收到一个错误的请求。这就是我想:在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对象来简化请求?我将不胜感激任何帮助或建议。

+0

尝试'$ .param(data);'它输出''SomeID = 18&Utc = null&Flags = 324“' – UnLoCo

回答

18

,这是有效的:

$.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/

1

为什么你需要回拨? (Ow等待,jsonp)我想先尝试以下内容:

$.getJSON("https://somewhere.com/AllGet?callback=?", data, function(result) { 
    alert(result); 
}); 

在萤火虫的某处,看看它是否会返回你所期望的。我不确定字符串作为数据是干什么的,但只是给一个对象工作得很好。

3

不使用JSON.stringfy,只是传递数据。

$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) { 
    alert(result); 
}); 
3

当将数据提供给一个jQuery GET请求时,它期待一个对象,而不是一个JSON字符串,用于构造查询字符串参数。试着改变你原来的代码,只是这样的:根据现场

$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) { 
    alert(result); 
}); 
0
$.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); 
     }); 
1

你不需要做JSON.stringfy,只是通过JSON对象,jQuery将构建你的URL参数与

$.getJSON("https://somewhere.com/AllGet?callback=?", data, function (result) { 
    alert(result); 
}); 
0

我试图编码JSON和它的工作。

不确定它是多么有效率或实用,分享它只是为了解决上述问题。

$.getJSON("https://somewhere.com/AllGet?data="+encodeURI(JSON.stringify(data)), function (result) { 
     alert(result); 
});