JQuery移动查询字符串问题在非pushState浏览器

JQuery Mobile Query String Issue in non pushState browsers

本文关键字:pushState 浏览器 问题 移动 查询 字符串 JQuery      更新时间:2023-09-26

我正在尝试将变量cid从JQuery Mobile beta 3的查询字符串中拉出来。

正常URL的示例如下/category.php吗?cid = 23

JQuery Mobile URL示例/#/category.php吗?cid = 23

在大多数浏览器中,由于JQuery Mobile Beta 3的url重写,我可以使用下面的函数正常地将变量从querystring中拉出来。但是IE不支持新的浏览器历史记录功能。https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

因此,我需要一种方法来拉出querystring从JQuery移动Url看到上面和下面的功能,我通常使用下面不能正常工作。

function getQuerystring(key) {
   var re=new RegExp('(?:''?|&)'+key+'=(.*?)(?=&|$)','gi');
   var r=[], m;
   while ((m=re.exec(document.location.search)) != null) r.push(m[1]);
   return r;
}

我要么寻找一个替代的正则表达式,可以找到哈希变量在不支持历史的浏览器。pushState或其他解决方案。我在文档中搜索了这个问题的解决方案,但没有找到任何东西。我认为这应该是一个已经被JQuery移动团队考虑和解决的问题,我可能只是错过了一些非常明显的东西。谢谢你的帮助。

Working Demo (I think)

  • http://jsfiddle.net/phillpafford/VXV3R/

相关链接:

  • 我如何在JavaScript中获得查询字符串值?

JS

$('#page2').live('pageshow', function(event, ui) {
    alert('Page 2 - CID: ' + getParameterByName('cid'));
});
function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/'+/g, ' '));
}

HTML(给链接添加rel="external")

<div data-role="page" id="home">
    <div data-role="content">
        <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="f">
            <li data-role="list-divider">
                Home Page
            </li>
            <li>
                <!-- 
                    Pass Parm Here before the hash page 
                    and treating link as external 
                -->
                <a href="?cid=1234#page2" rel="external">Page 2</a>
            </li>
        </ul>                
    </div>
</div>
<!-- page 2 -->
<div data-role="page" id="page2">
    <div data-role="content">
        <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="f">
            <li data-role="list-divider">
                Page 2
            </li>
            <li>
                <a href="?cid=4321#home">Home Page</a>
            </li>
        </ul>
    </div>
</div>

好了,这里有一个函数,将照顾这两种情况,无论你是在什么浏览器上,甚至你是什么方式使用JQuery移动。这段代码并不完美,我只是很高兴它目前的工作。当我更新函数时,我会回来在这里更新它。

首先,代码查看是否存在散列。如果有,它会在其中查找一个querystring,就像它是一个url一样。如果不是,它只是检查变量的url。这段代码用于检查特定的querystring变量,无论您在JQuery Mobile中检查它的状态如何。无论它是pagcreatepageshow还是在任何其他事件中,Weather JQuery Mobile Beta 3已经通过pushstate重写了url。

function getQuerystring(name) {
    var hash = document.location.hash;
    var match = "";
    if (hash != undefined && hash != null && hash != '') {
        match = RegExp('[?&]' + name + '=([^&]*)').exec(hash);
    }
    else {
        match = RegExp('[?&]' + name + '=([^&]*)').exec(document.location.search);
    }
    return match && decodeURIComponent(match[1].replace(/'+/g, ' '));
}