javascript 如何从父页面获取查询字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7962646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:52:53  来源:igfitidea点击:

how to get the querystring from a parent page?

javascriptasp.net

提问by user603007

i am using an iframe ipage in my parentpage. I would like to get the querystring in javascript of the parentpage?

我在我的父页面中使用 iframe ipage。我想在父页面的 javascript 中获取查询字符串?

回答by Marwan

I suggest to you to use my favourite function:

我建议你使用我最喜欢的功能:

 function getQueryString() {
                var queryStringKeyValue = window.parent.location.search.replace('?', '').split('&');
                var qsJsonObject = {};
                if (queryStringKeyValue != '') {
                    for (i = 0; i < queryStringKeyValue.length; i++) {
                        qsJsonObject[queryStringKeyValue[i].split('=')[0]] = queryStringKeyValue[i].split('=')[1];
                    }
                }
                return qsJsonObject;
            }

Just call it from the child window like this and act with the query string as an object.

只需像这样从子窗口调用它,并将查询字符串作为对象进行操作。

For example if you have the query string ?name=stackand you want to get it, try:

例如,如果您有查询字符串?name=stack并且想要获取它,请尝试:

getQueryString().name

This will return stack.

这将返回stack

回答by codifier

nice answer from @Marawan. - if it helps anyone... I extended this to choose the target as a parameter (self / parent)

@Marawan 的回答很好。- 如果它对任何人有帮助......我将其扩展为选择目标作为参数(自我/父母)

function getQueryString(target) {
    if ( target == 'parent' ) {
        var queryStringKeyValue = window.parent.location.search.replace('?', '').split('&');
    }
    else {
        var queryStringKeyValue = window.location.search.replace('?', '').split('&');
    }

    var qsJsonObject = {};
    if (queryStringKeyValue != '') {
        for (i = 0; i < queryStringKeyValue.length; i++) {
            qsJsonObject[queryStringKeyValue[i].split('=')[0]] = queryStringKeyValue[i].split('=')[1];
        }
    }
    return qsJsonObject;
}

eg.

例如。

getQueryString('parent').id;    // get iframe parent url ?id=foo
getQueryString().id;    // get this url ?id=foo