Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

javascript - "invalid label" Firebug error with jQuery getJSON

I'm making a jQuery $.getJSON request to another domain, so am making sure that my GET URI ends with "callback=?" (i.e. using JSONP).

The NET panel of Firebug shows that I am receiving the data as expected, but for some reason the Console panel logs the following error: "invalid label".

The JSON validates with JSONLint, so I doubt that there is anything truly wrong with the structure of the data.

Any ideas why I might be receiving this error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is an old post, but I'm posting a response anyway:

Let's assume you want to get the jSON code generated by the following file, "get_json_code.php":

<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>

Like you mentioned, $.getJSON() uses JSONP when you add a "jsoncallback=?" parameter to the required URL's string. For example:

$.getJSON("http://mysite.com/get_json_code.php?jsoncallback=?", function(data){ 
   alert(data);
});

However, in this case, you will get an "invalid label" message in Firebug because the "get_json_code.php" file doesn't provide a valid reference variable to hold the returned jSON string. To solve this, you need add the following code to the "get_json_code.php" file:

<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo $_GET['jsoncallback'].'('.json_encode($arr).')'; //assign resulting code to $_GET['jsoncallback].
?> 

This way, the resulting JSON code will be added to the 'jsoncallback' GET variable.

In conclusion, the "jsoncallback=?" parameter in the $.getJSON() URL does two things: 1) it sets the function to use JSONP instead of JSON and 2) specifies the variable that will hold the JSON code retrieved from the "get_json_code.php" file. You only need to make sure they have the SAME NAME.

Hope that helps,

Vq.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...