javascript - 我缺少什么来修复此 JSONP 代码?

标签 javascript jquery jsonp

我按照 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/

相关文章:

javascript - 时刻JS获得一年中第一周的正确周数

javascript - 使 <img> 元素出现在悬停时并保持在与被点击按钮的相同 ID 相对应的点击上

javascript - jsonp 和 POST 操作

javascript - $.getJSON(p) 远程请求失败

javascript - AngularJS中变量的动态名称

javascript - 你能为 Promises 定义一个 resolve 函数吗?

javascript - 带列的可折叠列表?

jquery - 如何向上移动寻找元素?

jquery - @require-ing jQuery 覆盖页面的 $ 变量

javascript - jQuery JSONP 不调用回调