试图从查询字符串中提取信息

时间:2014-03-25 12:35:43

标签: javascript

我是JavaScript的新手,我正在尝试从我创建的网络上的查询字符串中提取信息,如果我直接在页面上加载没有查询字符串的页面将加载但是一旦我从表单页面重定向到我正在解析它冻结和崩溃的页面......任何人都可以帮忙! :(

http://main.xfiddle.com/7d679c3a/Project1/Commission.php
http://main.xfiddle.com/7d679c3a/Project1/contactForm.php
http://main.xfiddle.com/7d679c3a/Project1/DiceRoll.php
http://main.xfiddle.com/7d679c3a/Project1/IsEven.php
http://main.xfiddle.com/7d679c3a/Project1/palindrome.php
http://main.xfiddle.com/7d679c3a/Project1/part1.php
http://main.xfiddle.com/7d679c3a/Project1/passwordStrength.php
http://main.xfiddle.com/7d679c3a/Project1/allinOne.php

JavaScript代码

var $ = function(id)
{
return document.getElementById(id); 
}

var formInfo = location.search();
    formInfo = formInfo.substring(1, formInfo.length);

while (formInfo.indexOf("+") != -1)
{
    formInfo = formInfo.replace("+", " ");  
}



while (formInfo.indexOf("=") != -1)
{
    formInfo.replace("=", " "); 
}

formInfo = decodeURI(formInfo);
formInfo.replace("firstname", "");  
formInfo.replace("lastname", "");   
formInfo.replace("phonenumber", "");    
formInfo.replace("postalcode", ""); 
formInfo.replace("startingmoney", "");

var infoArray = formInfo.split("&");

var firstName = infoArray[0];
var lastName = infoArray[1];
var phoneNumber = infoArray[2];
var postalCode = infoArray[3]; 
var startingMoney = infoArray[4];

 $("playername").innerHTML = firstName + " " +lastName;
 $("playerinfo").innerHTML = phoneNumber + " " + postalCode;
 $("money").innerHTML = " $$" + startingMoney;

HTML代码

<div id="fireinfo">
<p id="playername"></p><br/>
<p id="playerinfo"></p>
<p id="money"></p>
</div>

我想把我从查询字符串中获取的信息放入玩家姓名,玩家信息和金钱ID中。

1 个答案:

答案 0 :(得分:0)

使用此函数获取查询字符串值:

   function getQueryString(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), 
            results = regex.exec(window.location.search);

        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };

    var firstname = getQueryString('firstname');