This code is just stuck in the Body it does exactly what I expect but I don’t understand WHY.
Particularly I dont see how the webservice gets called, it looks like the script adds the call to the Head section and maybe reloads the page but I’m not sure and don’t like not knowing or what this line means – script.onload = script.onreadystatechange = function ()
Can anyone explain please?
var script = document.createElement("script"),
head = document.getElementsByTagName("head")[0],
url = "https://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/FindByPostcode/v1.00/json.ws?";
// Build the query string
url += "&Key=" + encodeURI(pca_Key);
url += "&Postcode=" + encodeURI(postcode);
url += "&CallbackFunction=PostcodeAnywhere_FindByPostcode_End";
script.src = url;
// Make the request
script.onload = script.onreadystatechange = function () {
if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
script.onload = script.onreadystatechange = null;
if (head && script.parentNode)
head.removeChild(script);
}
}
head.insertBefore(script, head.firstChild);
Stu
Basically, it’s making a JSONP call to get some data from postcodeanywhere.co.uk. JSONP uses
scriptelements. The script from postcodeanywhere.co.uk will call the function identified by theCallbackFunctionargument on the script URL, passing it a JavaScript object literal, something like this:You haven’t shown it, but presumably there’s a function with that name defined at global scope in the script making the call.
This is to work around the SOP, which doesn’t allow ajax calls cross-origin.
How it does it is by creating a
scriptelement, assigning it thesrcURL, appending it to the page, and then hooking thereadystateevent so it can clean up after itself by removing the element again. (That last bit isn’t quite what it could be, not all browsers fire thereadystateevent onscriptelements, to do this thoroughly you have to hook bothreadystateandload. Or do the cleanup in the callback. But having the script element lying around is harmless.) It should also be usingencodeURIComponent, notencodeURI. And there’s no need for the stuff with theheadelement, you can just append the script directly todocument.documentElement.