I have a jQuery AJAX call that works perfectly well:
$.ajax({
url: "http://exampleurl.com/sub/sub2/posts?api_key=ApIKeyGoEsHEre",
dataType: 'jsonp',
success: function(data){
filter(data); // Callback function
}
});
However I cannot get a pure JS version of this to work, the dataType: jsonp is giving me trouble. My attempts are as follows
This approach gives me an error of Unexpected token :, adding ?callback=filter to the end of the URL says the page is not found
var script = document.createElement('script');
script.src = 'http://exampleurl.com/sub/sub2/posts?api_key=ApIKeyGoEsHEre';
console.log(script);
document.body.appendChild(script);
My second approach; Gives me an error of Unexpected token : as well
function jsonp(url) {
var head = document.head;
var script = document.createElement("script");
script.setAttribute("src", url);
head.appendChild(script);
head.removeChild(script);
}
function jsonpCallback(data) {
filter(JSON.stringify(data));
}
jsonpCallback(jsonp("http://exampleurl.com/sub/sub2/posts?api_key=ApIKeyGoEsHEre"));
My third approach; Gives me an error of cannot load (the url). Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://exampleurl.com/sub/sub2/posts?api_key=ApIKeyGoEsHEre", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
filter(JSON.stringify(data));
console.log(JSON.stringify(data));
}
}
xmlhttp.send();
}
loadXMLDoc();
Where am I going wrong?
An attempt was made to reference a Node in a context where it does not exist.