使用jQuery / Javascript访问GET变量 [英] Access GET variables using jQuery/Javascript

查看:58
本文介绍了使用jQuery / Javascript访问GET变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道之前已经问过这个问题,但到目前为止我发布的所有解决方案都遇到了问题。我有一个看起来像这样的网址:

I know that this question has been asked before, but I have had trouble with all of the solutions posted so far. I have a url that looks like this:

http://localhost:3000/virgil/1/render_lesson?toggle=view

这是通过AJAX进行的Rails调用,但这无关紧要。每当我尝试一个应该为切换获取变量的函数时,当我将它打印到控制台日志时,我得到未定义。我试过这个函数

It is a Rails call through AJAX, but that should not matter. Everytime I try a function that is supposed to get the variable for "toggle" I get "undefined" instead when I print it to the consoles log. I have tried this function

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

But when I call console.log(getUrlVars()["toggle"]); I simply get undefined

我感谢任何帮助!

编辑:

添加我的代码的相关部分。这是一个Rails应用程序,使用AJAX进行调用。

Adding the relevant parts of my code. This is a Rails application, that makes the call using AJAX.

<%= link_to'查看课程',render_lesson_virgil_path(课程,:切换) =>:view),:remote =>是的,:class => 'toggle_lesson',:id => toggle_lesson#{course.id}%>

然后在它调用的javascript文件中:

And then in the javascript file that it calls:

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  %>");


推荐答案

这是我用于查询字符串的JS函数 - 希望它可以帮到你。

This is the JS function I use for query strings - hopefully it helps you.

function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

这篇关于使用jQuery / Javascript访问GET变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆