Reputation: 75
I have followed a JSONP example to send data to a cross-domain, however I get a
Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': 2 arguments required, but only 1 present.
on the 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);
Upvotes: 0
Views: 104
Reputation: 1074028
insertBefore
expects two arguments. 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:
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. You might want
this.parentNode.removeChild(this); // DOM
...or of course (as you've tagged your question jQuery):
$(this).remove(); // jQuery
...instead.
As you've tagged your question jquery
:
That said, jQuery has JSONP support built in, you don't have to write it again yourself:
$.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.
Upvotes: 3