这段代码只是停留在主体中,完全符合我的期望,但我不明白为什么。
特别是我看不到如何调用Web服务,它看起来像脚本将调用添加到Head部分,并可能重新加载页面,但是我不确定并且不喜欢不知道这行的含义-script.onload = script.onreadystatechange =函数()
谁能解释一下?
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);
斯图
最佳答案
基本上,它正在进行JSONP调用以从postcodeanywhere.co.uk获取一些数据。 JSONP使用script
元素。来自postcodeanywhere.co.uk的脚本将调用脚本URL上由CallbackFunction
参数标识的函数,并向其传递JavaScript对象文字,如下所示:
PostcodeAnywhere_FindByPostcode_End({
name: value
})
您没有显示它,但是大概在调用的脚本中有一个函数的名称在全局范围内定义。
这是为了解决SOP,它不允许ajax跨域调用。
通过创建
script
元素,为其分配src
URL,将其附加到页面,然后钩住readystate
事件,以便通过再次删除该元素可以对其进行清理,从而实现的功能。 (最后一点并不完全是,不是所有浏览器都在readystate
元素上触发script
事件,要彻底做到这一点,您必须同时钩住readystate
和load
。或者在回调中进行清理。但是要有script元素。躺在周围是无害的。)它也应该使用encodeURIComponent
,而不是encodeURI
。而且,不需要带有head
元素的东西,您只需将脚本直接附加到document.documentElement
即可。关于javascript - 这段JavaScript如何运作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8534070/