同源策略(http://baike.baidu.com/
HTML5 XDM
近年不断发展的HTML5规范对XDM-跨文档消息传送机制进行
_postMessage(message, targetOrigin, transfer)_函数有三个参数。第一个message表示要
比如下面的例子简单演示了使用postMessage()向内嵌
var iframWindow = document.getElementById(“
iframWindow.postMessage(“
接收方www.html5.org收到XDM消息会异步触发wi
window.addEventListener(“
if (event.origin == “http://www.infoq.com“) {
processMessage(event.data);
event.source.postMessage(“
}
});
easyXDM (https://github.com/
easyXDM包含两个基本对象。
easyXDM.Socket对象包装了传输栈,
服务端首先建立Socket:
var socket = new easyXDM.Socket({
onMessage**:function**(message, origin) {
//do something with message
}
});
var socket = new easyXDM.Socket({
remote**:** “http://path.to/provider/“, // the path to the provider
onMessage**:function**(message, origin) {
//do something with message
}
});
socket.postMessage(“hello world”);
easyXDM.Rpc对象允许创建带有代理对象进行远程方法调
在服务端配置被调用的远程对象:
var rpc = new easyXDM.Rpc({},
{
local**:** {
helloWorld**: function**(one, two, three, successFn, errorFn){
// here we expose a simple method with three arguments
// that returns an object
return {
this_is**:** “an object”
};
}
},
remote**:** {
helloWorld**:**{
// here we tell the Rpc object to stub a method helloWorld for us
}
}
});
rpc.helloWorld(1,2,3, function(response){
// here we can do something with the return value from helloWorld
}, function(errorObj){
// here we can react to a possible error
};
跨域资源请求
在web开发中跨域资源请求相当常用。借助XDM,
下面举例如何使用easyXDM来跨站点文件请求:站点clie
在客户端client.com/index.html引用eas
var socket = new easyXDM.Socket({
remote: “http://remote.com/agent.html“
onMessage:function(message, origin) {
var data = $.parseXML(message);
//do something with message data
}
});
在被请求的远程服务端remote.com/agent.
$.ajax({
type: “GET”,
url: “list.xml”,
dataType: “text”,
success: function (data) {
var socket = new easyXDM.Socket(
{
onReady: function(message, origin){ }
}
);
socket.postMessage(‘’ + data);
}
});
小结:easyXDM开源组件封装和支持HTML5的postM