jQuery 使用jQuery获取json数据返回无效标签错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1230897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:58:25  来源:igfitidea点击:

Using jQuery to get json data returns invalid label error

jsonjquery

提问by brendan

I have this code, and have also tried something similar using the $.getJson function:

我有这个代码,并且还使用 $.getJson 函数尝试了类似的东西:

jQuery(document).ready(function(){
    var kiva_url = "http://api.kivaws.org/v1/loans/newest.json";

    jQuery.ajax({
        type: "GET",
        url: kiva_url,
            data:"format=json", 
        success: function(data){
            alert("here");
            jQuery.each(data.loans, function(i, loan){
                jQuery("#inner_div").append(loan.name + "<br />");
            });
        },
        dataType: "jsonp",
        error: function(){
            alert("error");
        }
    });

});

When I look in Firebug it is returning an "invalid label" error. I've searched around a bit some people refer to using a parser to parse the results. I can see the results coming back in Firebug. Can someone point to an example of what I should be doing?

当我查看 Firebug 时,它返回“无效标签”错误。我搜索了一些人提到使用解析器来解析结果。我可以在 Firebug 中看到返回的结果。有人可以指出我应该做什么的例子吗?

The Firebug error:

萤火虫错误:

invalid label http://api.kivaws.org/v1/loans/newest.json?callback=jsonp1249440194660&_=1249440194924&format=json&Line 1

无效标签 http://api.kivaws.org/v1/loans/newest.json?callback=jsonp1249440194660&_=1249440194924&format=json&第 1 行

Sample output of what the json looks like can be found here: http://build.kiva.org/docs/data/loans

可以在此处找到 json 外观的示例输出:http: //build.kiva.org/docs/data/loans

采纳答案by brendan

Well I found the answer...it looks like kiva does not support jsonp which is what jquery is doing here -

好吧,我找到了答案......看起来 kiva 不支持 jsonp,这就是 jquery 在这里所做的 -

http://groups.google.com/group/build-kiva/browse_thread/thread/9e9f9d5df821ff8c

http://groups.google.com/group/build-kiva/browse_thread/thread/9e9f9d5df821ff8c

...we don't have plans to support JSONP. Supporting this advocates poor security practices and there are already some good ways to access the data from JavaScript that protect your application and your users. Here's a great article on the subject:

http://yuiblog.com/blog/2007/04/10/json-and-browser-security/

While the risk to Kiva lenders is low now since we are only dealing with public data, allowing private lender data to be imported via script tags is a risk further down the road. Our thought is the risk (and complexity added to create secure applications) is not worth the benefit to developers.

Writing a server-side proxy for the feeds you need is the most common solution to accessing data in browser-based applications. Some other tricks exist using iFrames. The best hope is the new breed of client- based technologies/standards that will let browser-based JavaScript access cross-domain resources securely ( http://dev.w3.org/2006/waf/access-control/http://json.org/JSONRequest.html). Some tools like BrowserPlus and Gears let you play with these today, but you won't be able to depend on these in the wild for a while.

As a final note, I'll point out that anyone using JSON responses in JavaScript should either parse JSON explicitly or validate the JSON before taking eval() to it. See here:

http://www.JSON.org/js.html

Linked from the page is a great reference implementation of the proposed ECMAScript JSON parser interface, JSON.parse().

Cheers, skylar

...我们没有计划支持 JSONP。支持这种做法提倡糟糕的安全实践,并且已经有一些很好的方法可以从 JavaScript 访问数据来保护您的应用程序和用户。这是关于这个主题的一篇很棒的文章:

http://yuiblog.com/blog/2007/04/10/json-and-browser-security/

虽然现在 Kiva 贷方的风险很低,因为我们只处理公共数据,但允许通过脚本标签导入私人贷方数据是一个进一步的风险。我们认为风险(以及为创建安全应用程序而增加的复杂性)不值得开发人员从中受益。

为您需要的提要编写服务器端代理是在基于浏览器的应用程序中访问数据的最常见解决方案。使用 iFrame 还存在其他一些技巧。最大的希望是新的基于客户端的技术/标准,它将让基于浏览器的 JavaScript 安全地访问跨域资源 ( http://dev.w3.org/2006/waf/access-control/ http:// json.org/JSONRequest.html)。现在您可以使用 BrowserPlus 和 Gears 之类的一些工具来使用这些工具,但在一段时间内您将无法依赖这些工具。

最后,我将指出,任何在 JavaScript 中使用 JSON 响应的人都应该在使用 eval() 之前显式解析 JSON 或验证 JSON。看这里:

http://www.JSON.org/js.html

从该页面链接的是所提议的 ECMAScript JSON 解析器接口 JSON.parse() 的一个很好的参考实现。

干杯,斯凯拉

回答by Kirbdawg

When you return the data, are you returning it with the correct content type and as a method?

当您返回数据时,您是否使用正确的内容类型和方法返回它?

You should return your data as follows (php 5 example):

您应该按如下方式返回数据(php 5 示例):

$return = "my_callback_method(" . json_encode( array('data'=>'your data etc') ). ")";

while (@ob_end_clean());
header('Cache-Control: no-cache');
header('Content-type: application/json');
print_r($return);

In your calling javascript code, you must have a method to match the callback method you returned, in this case:

在调用 javascript 代码中,您必须有一个方法来匹配您返回的回调方法,在这种情况下:

function my_callback_method( returned_data ){
}

So, your complete calling js should look something like the following

因此,您的完整调用 js 应如下所示

jQuery(document).ready(function(){
var kiva_url = "http://api.kivaws.org/v1/loans/newest.json";

jQuery.ajax({
    type: "GET",
    url: kiva_url,
        data:"format=json", 
    dataType: "jsonp",
    error: function(xmlhttp,error_msg){
            alert("error"+error_msg);
    }
});

function my_callback_method( data ){
   alert("here");
   if( data && typeof(data) == 'object') ){
     jQuery.each(data.loans, function(i, loan){
         jQuery("#inner_div").append(loan.name + "<br />");
     });
   }
}

});

回答by Abu Aqil

回答by SolutionYogi

Where does the error occur? Does error occur when you try to loop through the ajax data and append it to the inner_div? If yes, please show us what the data.loans look like.

错误发生在哪里?尝试遍历ajax数据并将其附加到inner_div时是否发生错误?如果是,请向我们展示 data.loans 的样子。

Also, there is a typo in your code:

此外,您的代码中有一个错字:

            jQuery.each(data.loans, function(i, loan){
                    jQuery("#inner_div").append(loan.name + "<br />"); //It should be loan.name and not laon.name
            });
    },

回答by Duc Bui

This is the answer http://forum.jquery.com/topic/jquery-getjson-invalid-label

这是答案 http://forum.jquery.com/topic/jquery-getjson-invalid-label

Simply wrap your Json response with your callback request E.g. jQuery16203473509402899789_1315368234762({"Code":200,"Message":"Place added successfully","Content":""});where jQuery16203473509402899789_1315368234762is your callback request (you can get it via querystring) {"Code":200,"Message":"Place added successfully"}is your JSON response

只需将您的 Json 响应与您的回调请求包装在一起,例如您的回调请求jQuery16203473509402899789_1315368234762({"Code":200,"Message":"Place added successfully","Content":""});在哪里 jQuery16203473509402899789_1315368234762(您可以通过查询字符串获取) {"Code":200,"Message":"Place added successfully"}是您的 JSON 响应