doutan5724 2011-06-24 04:15
浏览 133
已采纳

将$ _GET变量赋给JS变量

www.mywebsite.com/?foo=bar

How can I get the value of foo into a Javascript variable?

  • 写回答

4条回答 默认 最新

  • donglianjiang9321 2011-06-24 04:18
    关注

    You don't even need PHP for that. Basically, you can parse window.location.href to get the value of a GET URL parameter into a JavaScript variable.

    There is plenty of code online, you can use for example this:

    function getUrlParameter( 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];
    }
    

    To get the value of foo, just call getUrlParameter("foo") in your JavaScript code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?