简体   繁体   English

解决此JSONP代码时我缺少什么?

[英]What am I missing to fix this JSONP code?

I have followed a JSONP example to send data to a cross-domain, however I get a 我已经按照JSONP示例将数据发送到跨域,但是我得到了一个

Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': 2 arguments required, but only 1 present. 未捕获的TypeError:无法在“节点”上执行“ insertBefore”:必需2个参数,但仅存在1个。

on the head.insertBefore(script); head.insertBefore(script); line. 线。

What am I missing here? 我在这里想念什么?

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 expects two arguments. insertBefore需要两个参数。 I'm pretty sure you meant 我很确定你的意思

head.appendChild(script);

instead of 代替

head.insertBefore(script);

Separately, note that the remove method of DOM elements is a relatively recent addition, so this line: 另外,请注意,DOM元素的remove方法是相对较新的添加,因此此行:

this.remove();

...in your onload handler may fail on older browsers (I'm looking at you, IE8), since this there is a DOM element, not a jQuery instance. ...在您的onload处理程序中,在旧版浏览器上可能会失败(我正在向您看,IE8),因为this是一个DOM元素,而不是jQuery实例。 You might want 你可能想要

this.parentNode.removeChild(this); // DOM

...or of course (as you've tagged your question jQuery): ...或者当然是(如您为问题jQuery标记的):

$(this).remove();                  // jQuery

...instead. ...代替。


As you've tagged your question jquery : 当您标记了问题jquery

That said, jQuery has JSONP support built in , you don't have to write it again yourself: 也就是说,jQuery 内置了 JSONP支持,您无需自己重新编写:

$.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 will manage creating a function for the JSONP endpoint to call back, adding the callback= to the URL, etc. jQuery将管理为JSONP端点创建一个函数以进行callback= ,将callback=添加到URL等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM