總有一款適合你。。。
如果想了解iframe有關傳值請參看之前文章:iframe跨不跨域通訊方式集合;
這篇主要是說說其他幾種頁面之間傳值的實現:
實現一:url傳值
這種傳值方式就是通過在url後面增加參數,然後打開該url後頁面獲取參數信息,再用js進行處理。
main.html:
<input id='myText'><button onClick='post()'>
<script>
function post(){
url= "other.html?name="+escape(document.getElementById('myText').value);
location.href=url;
}
</script>
other.html:<script>
var url=location.search,obj={};
if(url.indexOf("?")!=-1){
var str = url.substr(1)
strs= varstr.split("&");
for(var i=0;i<strs.length;i++){
obj[strs[i].split("=")[0]]=unescape(strs[ i].split("=")[1]);
}
}
alert(obj.name)
</script>
實現二:cookie傳值:
實現思想就是通過document.cookie進行設置值以及取值
main.html
<script>
function setCookie(name,value){
var Days = 30;
var exp = new Date();
exp.setTime(exp.getTime() +Days*24*60*60*1000);
document.cookie = ""+name +"="+ escape (value) + ";expires=" + exp.toGMTString();
}
setCookie('name','yuchao');
location.href = "other.html";
</script>
other.html:
<script>
function getCookie(name){
var arr =document.cookie.match(new RegExp("(^|)"+name+"=([^;]*)(;|$)"));
if(arr !=null) return unescape(arr[2]);
return null;
}
document.getElementById(xx).innerHTML=getCookie('name');
</script>
這裏需要注意的是,如果你在靜態頁面下測試chrome瀏覽器是無法讀取設置cookie的,也就是說如果要實現該傳值必須將運行環境放到服務器上。
實現三:showModalDialog方式:
使用方式:
var rtn=window.showModalDialog(url ,arguments,style);
參數說明:
url要新打開的窗口鏈接,爲防止緩存一般都會加上?random="+Math.random()
arguments傳遞參數內容,參數類型不限,可以是對象數組等,例如{name:xxx}
style打開窗口樣式控制,用來控制新窗口外觀等信息,可以使用下面一個或幾個
參數名 | 參數介紹 |
dialogHeight | 對話框高度,不小於100px |
dialogWidth | 對話框寬度 |
dialogLeft | 離屏幕左的距離 |
dialogTop | 離屏幕上的距離 |
center | { yes | no | 1 | 0 } : 是否居中,默認yes,但仍可以指定高度和寬度 |
help | {yes | no | 1 | 0 }: 是否顯示幫助按鈕,默認yes |
resizable | {yes | no | 1 | 0 } [IE5+]:是否可被改變大小。默認no |
status | {yes | no | 1 | 0 } [IE5+]:是否顯示狀態欄。默認爲yes[ Modeless]或no[Modal] |
scroll | { yes | no | 1 | 0 | on | off }:是否顯示滾動條。默認爲yes |
接受參數頁面調用window.dialogArguments;取得傳遞參數,
關閉彈出頁面後也可以利用window.returnValue進行回傳值。
舉例如下:
main.html:
<script>
function dialogPost(){
var rtn=window.showModalDialog('other.html' ,{name:'yuchao',sex:'male'} );
document.getElementById('dialag').innerHTML='彈出窗口返回數據爲:'+rtn;//返回nihao
}
</script>
other.html:
<button onClick='closeNow()'>
<script>
var obj = window.dialogArguments;
alert("您傳遞的name爲:" + obj.name)
function closeNow(){
window.returnValue='nihao';
window.close();
}
</script>
特別說明:利用該方式可以在靜態頁面下打開一個窗口,但是不能在靜態下進行傳值,也需要放置服務器上纔可。
實現四:postMessage
html5中一種先進的通訊方式 : 詳見之前一篇文章