开发者

Is there a JQuery or JS equivalent to PHP's $name = $_GET['name']

开发者 https://www.devze.com 2023-01-21 03:35 出处:网络
I\'m trying to figure out a way to read GET method information from a form with javascript. Our IT department has our servers on lockdown, and as the web team we can only use javascript to accomplish

I'm trying to figure out a way to read GET method information from a form with javascript. Our IT department has our servers on lockdown, and as the web team we can only use javascript to accomplish our tasks. I'd use PHP if I could, but I can't.

What I need to do is read data sent via GET method in js if possible, so that I can assign the data into variables, and use it on individual pages after a user takes action开发者_开发问答 on a form.

ie. if data is sent in the url http://somesite.com?add_to_cart=true&items=10

Any help would be appreciated!


function getQuerystring(key, default_)
{
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

var addtocart = getQuerystring('add_to_cart','false');

source: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx


This page has a good run down. You don't need jQuery to do it. Their jQuery version is:

$.extend({
  getUrlVars: function(){
    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;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

Use it with:

// Get object of URL parameters
var allVars = $.getUrlVars();

// Getting URL var by its nam
var byName = $.getUrlVar('name');
0

精彩评论

暂无评论...
验证码 换一张
取 消