我按照 JSONP 示例将数据发送到跨域,但是我得到了
Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': 2 arguments required, but only 1 present.
在 head.insertBefore(script);
行上。
我在这里缺少什么?
function requestJSONP(url) {
// create script with passed in URL
var script = document.createElement('script');
script.src = url;
// after the script is loaded (and executed), remove it
script.onload = function () {
this.remove();
};
// insert script tag into the DOM (append to <head>)
var head = document.getElementsByTagName('head')[0];
head.insertBefore(script);
}
function processWeather(data) {
alert(data);
}
var url = 'http://www.domain.com/urls.php?callback=processWeather&format=json&cookie=jtyh65&url=thispage&key=765';
requestJSONP(url);
最佳答案
insertBefore
需要两个参数。我很确定你的意思是
head.appendChild(script);
而不是
head.insertBefore(script);
另外,请注意 DOM 元素的 remove
方法是最近添加的,因此这一行:
this.remove();
...在旧版浏览器上,您的 onload
处理程序可能会失败(我正在看着您,IE8),因为 this
有一个 DOM 元素,而不是jQuery 实例。您可能想要
this.parentNode.removeChild(this); // DOM
...或者当然(因为你已经标记了你的问题 jQuery):
$(this).remove(); // jQuery
...相反。
<小时/>当您标记您的问题jquery
时:
也就是说,jQuery 有 JSONP 支持 built in ,您不必自己重新编写:
$.ajax({
url: 'http://www.domain.com/urls.php?&format=json&cookie=jtyh65&url=thispage&key=765',
dataType: 'jsonp',
success: function(data) {
// Use `data`, it's already been parsed for you
},
error: function() {
// Something didn't work
}
});
jQuery 将管理为 JSONP 端点创建回调函数,将 callback=
添加到 URL 等。
关于javascript - 我缺少什么来修复此 JSONP 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30054703/