我知道之前已经问过这个问题,但到目前为止我发布的所有解决方案都遇到了问题。我有一个看起来像这样的网址:
http://localhost:3000/virgil/1/render_lesson?toggle=view
这是通过AJAX调用Rails,但这无关紧要。每当我尝试一个应该为“切换”获取变量的函数时,当我将它打印到控制台日志时,我得到“未定义”。我试过这个功能
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
当我致电console.log(getUrlVars());
时,我得到["http://localhost:3000/"]
但是当我致电console.log(getUrlVars()["toggle"]);
时,我只是得到undefined
我感谢任何帮助!
编辑:
添加我的代码的相关部分。这是一个Rails应用程序,它使用AJAX进行调用。
<%= link_to 'View Lessons', render_lesson_virgil_path(course, :toggle => :view), :remote => true, :class => 'toggle_lesson', :id => "toggle_lesson#{course.id}" %>
然后在它调用的javascript文件中:
function $_GET( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
console.log($_GET('toggle')); //This is where it prints the incorrect value to the log, regardless of the function I use.
$("#Course<%= @course.id %>").append('<div id="Lesson<%= @course.id %>" class="render_lesson"></div>');
$("#Lesson<%= @course.id %>").html("<%= escape_javascript(render( :partial => "lesson" )).html_safe %>");
答案 0 :(得分:3)
这是我用于查询字符串的JS函数 - 希望它可以帮助你。
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
答案 1 :(得分:0)
试试这个(我只更改了第4行 - “var hashes ......”):
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.valueOf().split('?').slice(1)[0].split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
答案 2 :(得分:-2)
我在我的1个项目中使用它..
function $_GET( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
看起来像PHP $_GET['']
...因为我喜欢PHP:D
用法示例:
网址:index.php?page=newone&id=4&cat=15
Javascript:alert($_GET('page')); // newone