How to write JSONP Ajax request on pure js?
In this particular case, you aren't making an ajax call at all, instead you're making a JSONP request. Luckily, these are incredibly easy to replicate and work in all browsers.
var s = document.createElement("script"),
callback = "jsonpCallback_" + new Date().getTime(),
url = "http://forexplay.net/ajax/quotes.php?callback=" + callback;
window[callback] = function (data) {
// it worked!
console.log(data);
};
s.src = url;
document.body.appendChild(s);
Get remote JSON without Jquery?
From vimeo's documentation
http://vimeo.com/api/docs/simple-api
It looks like you can put a ?callback=myfunction parameter on the end of the url to do a jsonp type of callback. So your code would maybe look something like this.
function myfunction(data) {
alert(data);
}
var script = document.createElement('script');
script.src = theUrlToMakeTheRequest + '?callback=myfunction';
document.getElementsByTagName('head')[0].appendChild(script);
Their downloads page looks to have examples for just what you are trying to do.
http://vimeo.com/api/docs/downloads
How to perform Ajax call with JSONP request in JavaScript?
I get error as Reason: CORS header ‘Access-Control-Allow-Origin’
missing.
This is because you're using XMLHttpRequest
and usage of XMLHttpRequest
requires CORS. The JSONP
technique doesn't involve usage of XMLHttpRequest
. The trick in JSONP is to create a script
tag and let a browser load that script:
var script = document.createElement('script');
script.src = '//domain.com/path/to/jsonp?callback=my_callback_method'
document.getElementsByTagName('head')[0].appendChild(script);
Also, you need to create a global function, in your case its my_callback_method
, and call it from the jsonp script.
Certainly, you server side should have implementation that when a request to //domain.com/path/to/jsonp
is obtained, it should return a js document with a call to a global function specified in callback=my_callback_method
:
my_callback_method()
Making and handling JSONP request using JavaScript
Here's a small example fetching data from a google spreadsheet:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>jsonp</title>
</head>
<body>
<span></span>
<script>
//this function is the callback, it needs to be a global variable
function readResponse(response){
document.getElementsByTagName('SPAN')[0].innerHTML = response.feed.entry.length + ' entries returned';
console.log(response);
}
(function(){
//note the "readResponse" at the end
var src = 'http://spreadsheets.google.com/feeds/list/o13394135408524254648.240766968415752635/od6/public/values?alt=json-in-script&callback=readResponse',
script = document.createElement('SCRIPT');
script.src = src;
document.body.appendChild(script);
})();
</script>
</body>
</html>
One comment related to this example. If you want to play with your own google spreadsheet, you need to both share it as public, and publish it.
Is it possible to make a secure JSONP request?
Yes!
It is possible. One way to do it would be to use WebWorkers. Code running in WebWorkers has no access to the DOM or other JavaScript code your page is running.
You can create a WebWorker and execute the JSONP request with it, then terminate it when you're done.
The process is something like this:
Create a WebWorker from a blob with the URL to request
Use
importScripts
to load the JSONP request with a local callbackWhen that callback executes, post a message back to the script, which in turn will execute the actual callback message with the data.
That way, an attacker would have no information about the DOM.
Here is a sample implementation:
// Creates a secure JSONP request using web workers.
// url - the url to send the request to
// data - the url parameters to send via querystring
// callback - a function to execute when done
function jsonp(url, data, callback) {
//support two parameters
if (typeof callback === "undefined") {
callback = data;
data = {};
}
var getParams = ""; // serialize the GET parameters
for (var i in data) {
getParams += "&" + i + "=" + data[i];
}
//Create a new web worker, the worker posts a message back when the JSONP is done
var blob = new Blob([
"var cb=function(val){postMessage(val)};" +
"importScripts('" + url + "?callback=cb" + getParams + "');"],{ type: "text/javascript" });
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
// When you get a message, execute the callback and stop the WebWorker
worker.onmessage = function (e) {
callback(e.data);
worker.terminate();
};
worker.postMessage(getParams); // Send the request
setTimeout(function(){
worker.terminate();//terminate after 10 seconds in any case.
},10000);
};
Here is sample usage that works in JSFiddle:
jsonp("http://jsfiddle.net/echo/jsonp", {
"hello": "world"
}, function (response) {
alert(response.hello);
});
This implementation does not deal with some other issues but it prevents all access to the DOM or the current JavaScript on the page, one can create a safe WebWorker environment.
This should work on IE10+, Chrome, Firefox and Safari as well as mobile browsers.
Related Topics
How to Update State.Item[1] in State Using Setstate
Jquery Checkbox Change and Click Event
Add a "Hook" to All Ajax Requests on a Page
How to Create an Https Server in Node.Js
Expression Inside Switch Case Statement
Get Video Duration When Input a Video File
Refresh a Div That Has a Google Ad Inside It
How Filereader.Readastext in HTML5 File API Works
Ignore Mouse Interaction on Overlay Image
Enter Key Press Behaves Like a Tab in JavaScript
Is It Safe to Store a Jwt in Localstorage with Reactjs
How to Get the Function Name from Within That Function
How to Sort an Array of Objects with Jquery or JavaScript
How Does _Proto_ Differ from Constructor.Prototype
Filter Array of Objects with Another Array of Objects
Html5 Check If Audio Is Playing
Error: Failed to Execute 'Appendchild' on 'Node': Parameter 1 Is Not of Type 'Node'