繁体   English   中英

javascript从URL读取变量值

[英]javascript read variable value from URL

当我将数据从一页发布到另一页时,如何将其放入dom。

说网址是www.test.com/?xxx=1234&a=122

如何获取xxx和DOM中值?

这是有关您所要执行的一种方法的基本教程:

http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

基本上,您将位置字符串从url拆分为一个数组,并在?后用&分隔。 标志。

这是该页面中执行此操作的代码:

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash; 
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); // cut the URL string down to just everything after the ?, split this into an array with information like this: array [0] = "var=xxx"; array [1] = "var2=yyy";

   //loop through each item in that array
    for(var i = 0; i < hashes.length; i++)
    {
        //split the item at the "="
        hash = hashes[i].split('=');

        //put the value name of the first variable into the "vars" array
        vars.push(hash[0]);

        //assign the value to the variable name, now you can access it like this:
        // alert(vars["var1"]); //alerts the value of the var1 variable from the url string
        vars[hash[0]] = hash[1];
    }
    return vars;
}

我添加了一些评论来解释它。

只需使用javascript的window.location.search属性即可( 此处有更多详细信息)。

var str = window.location.search;

现在,您可以使用substringsplit类的字符串操作功能来获取所需的文本,该文本可以在DOM内部使用。

URL中的参数可用作window.location对象的搜索属性。 将其转换为易于访问的对象并不难:

function getURLValues() {

  var search = window.location.search.replace(/^\?/,'').replace(/\+/g,' ');
  var values = {};

  if (search.length) {
    var part, parts = search.split('&');

    for (var i=0, iLen=parts.length; i<iLen; i++ ) {
      part = parts[i].split('=');
      values[part[0]] = window.decodeURIComponent(part[1]);
    }
  }
  return values;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM