Is it possible to use the postMessage()
method in Javascript to do cross-domain POST
, GET
, PUT
, etc. calls? If so, how? And how do I pass headers and data?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
This is a two way implementation, meaning that the page you want to call needs to have a callback that listens to such a message and give an appropriate response. You can't simply use it as a swap replacement for AJAX. The best method for that is to use a server-side proxy.
See this page for an explanation of how postMessage
works.
回答2:
Yes, it is possible.
There is a nice demo of what exactly you want, here
document.getElementById("iframe").contentWindow.postMessage(
document.getElementById("message").value,
"http://anotherdomain.com"
);
handled on the second side with
window.onmessage = function(e){
if ( e.origin !== "http://html5demos.com" ) {
return;
}
document.getElementById("test").innerHTML = e.origin + " said: " + e.data;
};