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

时间:2015-05-05 13:41:48

标签: javascript jquery jsonp

我已经按照JSONP示例将数据发送到跨域,但是我得到了

  

未捕获的TypeError:无法在'Node'上执行'insertBefore':2   需要参数,但只有1个存在。

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);

1 个答案:

答案 0 :(得分:3)

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等。

相关问题