将JSON数据传递到jQuery中的.getJSON

Passing JSON data to .getJSON in jQuery?

本文关键字:jQuery 中的 getJSON JSON 数据      更新时间:2023-09-26

我试图将一个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);
 });