$.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响应(我知道它是有效的)[为了清晰起见截断]
{ "records": [ { "service_offering": "","number": "INC0000009" },{ "service_offering": "","number": "INC0000010" } ] }
Firebug显示错误“无效标签
https://test.com/incident.do?JSON&callback=jsonp1279049933243&sysparm_action=getRecords
第1行
我怎样才能解决这个问题?
谢谢!
解决方法
你的回答是JSON,这是有效的,但这不是jQuery所期待的.当你指定& callback =?在URL中,jQuery期待一个JSONP响应,看起来不同,你的响应应该是
jsonp1279049933243({ "records": [ { "service_offering": "","number": "INC0000009" },{ "service_offering": "","number": "INC0000010" } ] });
指定callback =时会发生什么?是jQuery为您的成功函数生成一个名称,在本例中为jsonp1279049933243,JSONP只需生成一个< script>即可.在页面中标记,所以当它获取该URL时,它实际上只包含一个JavaScript文件,运行一个函数,而不是这个:
<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加载的,但无效的语法/标签错误是相同的.