2016-10-13 4 views
2

commit_PNG.htmlというメインのhtml文書があります。この文書では、他のhtml文書で使用したい2つの単純な文字列変数があります。 popup.html。現時点で私はこのような関数を持っています:1つのhtml文書から別のhtml文書にJavaScriptを使って変数を転送する

<script type="text/javascript"> 
    function PopUpFenster(id) {   
     myWindow = window.open('popup.html?id='+id, 'Info window', 'height=350, width=800'); 
    } 
</script> 

2番目のhtmlドキュメントでは、文字列変数を扱いたいと思います。私はpopup.htmlにこのような何かを動作するソリューションが必要です:

var string1 = "http://www.test.com/"+ commit_PNG.stringvariable1; 
var string2 = "http://www.test.com/"+ commit_PNG.stringvariable2; 

私はよく分からないが、私はどちらかcommit_PNG.htmlから直接それらを取るか、またはそれらにwindow.open()方法で誰かを解析する必要があります。

+0

これで、string1とstring2をポップアップウィンドウに渡しますか? – Pranay

+0

ポップアップウィンドウに直接は表示されません。私はそれらを使って、2番目のhtmlドキュメントに動的なURLを作りたいと思っています。後でそのURLを表示すると、そのポップアップウィンドウに表示されるリソースが表示されます。 –

答えて

1

このようなJSONオブジェクトを転送するために、ハッシュ部分を使用します。

commit_PNG.htmlで:

var myStrings = { 
str1:"my first str", 
str2:"my second str" 
} 

function PopUpFenster(id) { 
     var myUrl = "popup.html?id="+id+"#"+encodeURIComponent(JSON.stringify(myStrings)); 

     window.open(myUrl , "Info window", "height=350, width=800"); 
    } 

次に、あなたのpopup.htmlにだけ実行します。

var myData = JSON.parse(decodeURIComponent(window.location.hash.substring(1))); 
alert(myData.str1 + " " + myData.str2); 

をそれが通過するための素晴らしい方法ですURLの日付。 JSONオブジェクトを渡すと、encodeURIComponentでstringifyを使用すると、URLの安全な文字列になります。 ハッシュ部分を使用して、サーバーに送信されていないことを確認します。

+1

完璧に作業しました。私は欠落した '='のように少し編集しました。 迅速なアンサーに感謝します! –

1

commit_PNG.html

<script type="text/javascript"> 
    function getVariables(){ 
     return { 
      stringvariable1: 'v1', 
      stringvariable2: 'v2' 
     }; 
    } 

    function PopUpFenster(id) {   
     myWindow = window.open('popup.html?id='+id, 'Info window', 'height=350, width=800'); 
    } 
</script> 

popup.html

<script type="text/javascript"> 
    var parentWindow = window.opener; 
    var variables = parentWindow.getVariables(); 

    var string1 = "http://www.test.com/"+ variables.stringvariable1; 
    var string2 = "http://www.test.com/"+ variables.stringvariable2; 
</script> 
0

function getParameterByName(name, url) { 
 
    if (!url) url = window.location.href; 
 
    name = name.replace(/[\[\]]/g, "\\$&"); 
 
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), 
 
     results = regex.exec(url); 
 
    if (!results) return null; 
 
    if (!results[2]) return ''; 
 
    return decodeURIComponent(results[2].replace(/\+/g, " ")); 
 
} 
 
//Sample t 
 

 
// query string: ?foo=lorem&bar=&baz 
 
var foo = getParameterByName('foo'); // "lorem" 
 
var bar = getParameterByName('bar'); // "" (present with empty value) 
 
var baz = getParameterByName('baz'); // "" (present with no value) 
 
var qux = getParameterByName('qux'); // null (absent)

関連する問題