使用jQuery从URL获取查询字符串并根据该操作执行操作

时间:2014-08-28 01:36:53

标签: javascript jquery html

我在电子邮件中有一个链接,指向用户访问网页。除非单击按钮,否则在此网页上会隐藏一个弹出窗口;然后jQuery显示div。

我已经搜索了一种使用jQuery从URL中获取查询字符串的方法无济于事。我知道用PHP会是一个简单的$ query = $ _GET ['query'],但我不知道如何用jQuery来实现这个目的。

我需要检查一个查询字符串,比如“?popUp = true”,如果查询字符串存在,则用jQuery显示该div。

有没有办法可以将PHP GET变量传递给jQuery? 我很困惑。

2 个答案:

答案 0 :(得分:0)

jQuery与它无关;它只是简单的Javascript:

var query = window.location.search;

或者只是location.search。从Javascript控制台执行window.location以查看what all is there

所以:

$(document).ready(function(){
    if (location.search.indexOf('popUp=true') > -1)) {
        doPopUp(); // run your code.
    }
});

MDN

答案 1 :(得分:0)

当然,我们可以通过拆分从url获取查询参数,它是纯java脚本。有一般方法可以做到:http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html

但是如果你只需要[popup = true]来使用jquery,你最好使用hash。

URL:

http://.../yourscript.php#popup

你的jquery代码:

if(window.location.hash) {
 // Fragment exists, show popup
} else {
  // Fragment doesn't exist, do nothing
}
相关问题