我知道这个问题之前已经被问过了,但是到目前为止我发布的所有解决方案都遇到了问题。我有一个像这样的网址:使用jQuery/Javascript访问GET变量
http://localhost:3000/virgil/1/render_lesson?toggle=view
这是一个Rails通过AJAX调用,但这应该不重要。每次我尝试一个应该得到“切换”变量的函数时,我将其打印到控制台日志中时会得到“未定义”。我曾尝试这个功能
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 %>");
可能重复[如何获得与jQuery GET和POST变量?](http://stackoverflow.com/questions/439463/how-to-get-get - 和后变量与jQuery) – Bozho 2012-04-03 21:34:06
和http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery – Bozho 2012-04-03 21:34:22
我改变你的函数接受一个URL字符串,而不是从窗口抓取它。位置。我把你的URL作为一个字符串推入,它对我有用;我得到了一个具有“切换”键和“查看”值的数组。 – SuperJumbo 2012-04-03 22:14:12