jQuery get的JSON响应会引发“无效标签" [英] JSON response from jQuery get raises "Invalid label"
问题描述
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', "Basic YWRtaW46YWRtaW4=");
},
url: "https://test.com/incident.do?JSON&callback=?&sysparm_action=getRecords",
dataType: "json",
contentType: "application/json",
method: 'GET',
success: function(a,b,c) {
alert(a);
}
});
按下按钮即可调用此函数... Firebug显示我得到了这个JSON响应(我知道这是有效的)[为清楚起见,已截断]
I call this function with a button press... Firebug shows that I get this JSON response (which I know is valid) [truncated for clarity]
{
"records": [
{
"service_offering": "",
"number": "INC0000009"
},
{
"service_offering": "",
"number": "INC0000010"
}
]
}
Firebug显示错误无效标签 https://test.com/incident.do?JSON&callback= jsonp1279049933243& sysparm_action = getRecords 第1行
Firebug shows the error "invalid label https://test.com/incident.do?JSON&callback=jsonp1279049933243&sysparm_action=getRecords Line 1
我该如何解决? 谢谢!
How can I fix this? Thanks!
推荐答案
您的响应是JSON,这是有效的,但这不是jQuery想要的.当您在URL中指定&callback=?
时,jQuery期待的是JSONP响应,该响应看起来有所不同,您的响应应该为
Your response is JSON, which is valid, but that's not what jQuery's looking for. When you specify &callback=?
in the URL, jQuery is expecting a JSONP response, which looks different, your response should be
jsonp1279049933243({
"records": [
{
"service_offering": "",
"number": "INC0000009"
},
{
"service_offering": "",
"number": "INC0000010"
}
]
});
当您指定callback=?
时会发生什么,就是jQuery为您的success
函数生成一个名称,在本例中为jsonp1279049933243
,JSONP的工作原理是在页面中生成一个<script>
标记,因此当它获取该标记时url,实际上只是包含一个JavaScript文件,运行一个函数,而不是这样:
What happens when you specify callback=?
is that jQuery generates a name for your success
function, in this case jsonp1279049933243
, JSONP works by just generating a <script>
tag in the page, so when it fetches that url, it's really just including a JavaScript file, running a function, but instead of this:
<script type="text/javascript">
jsonp1279049933243({ "records": [....] });
</script>
现在有效的是:
<script type="text/javascript">
{ "records": [....] }
</script>
...这不是有效的JavaScript.现在当然可以通过src=https://test.com/incident.do?JSON&callback=jsonp1279049933243&sysparm_action=getRecords
加载了,但是无效的语法/标签错误是相同的.
...which isn't valid JavaScript. Now of course it's loaded via src=https://test.com/incident.do?JSON&callback=jsonp1279049933243&sysparm_action=getRecords
, but the invalid syntax/label error is the same.
这篇关于jQuery get的JSON响应会引发“无效标签"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!