如何将多个变量作为查询字符串参数传递

时间:2019-11-05 17:28:05

标签: javascript jquery

我正在使用以下Javascript函数。仅当值为数字时才有效。我的意思是,如果它是数字,则仅返回值。例如:

var ldInstID = getParameterByName("ID")

如果ID是一个数字,那么它将起作用并将其值分配给变量,但是如果ID是一个字符串,则它将不起作用。请帮忙使它也适用于字符串。 我在SharePoint列表编辑页上使用它,其中ID是列表列值。我想捕获另一个列城市,并将其作为href查询字符串以及ID传递。 在所附的图像中,您可以看到ldInstID为空白

<!--
    Name: dispParent.js
-->

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>


<script type="text/javascript">

jQuery(document).ready(function($) {

    //get the ID for the Issue from the Query String
   // var issueID = getParameterByName("ID");
	var ldInstID = getParameterByName("LeadInsitution");
    //find the element with the "Add new item" link.
    //note that if you have more than one list on your page, this just finds the first one
    var anchorElement = $("a[title='Add a new item to this list or library.']");
    
    //modify the "Add new item" link to call the "NewItem2" function and pass in the Issue ID. 
   //Be sure to put the path to your site below. You can use relative URL to the web application or the FQDN
  //  $(anchorElement).attr("href","javascript:NewItem2(event,'URL/Lists/Time/NewForm.aspx?IssueID="  + issueID +  "');");
   // $(anchorElement).attr("href","javascript:NewItem2(event,'URL/NewForm.aspx?IssueID="  + issueID + "&LdInst" + LdInst + "');");
	  $(anchorElement).attr("href","javascript:NewItem2(event,'URL/NewForm.aspx?LdInstID="  + ldInstID +  "');");
    //remove the "onclick" attribute from the anchor element as we aren't using it anymore
    $(anchorElement).removeAttr("onclick");

});


// no, I didn't write this function from scratch, I found it at
// http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
// http://www.sharepointhillbilly.com/Lists/Posts/Post.aspx?ID=26
function getParameterByName(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 decodeURIComponent(results[1].replace(/\+/g, " "));
}

</script>

variable passed-ID Variable passed- ldInstID

1 个答案:

答案 0 :(得分:0)

通过ID从URL获取参数:

function getURLParameter(parameterName) {
    let result = null, temp = [];
    location.search
        .substr(1)
        .split('&')
        .forEach(function (item) {
            temp = item.split('=');
            if (temp[0] === parameterName)
                result = decodeURIComponent(temp[1]);
        });

    return result;
}

如果我的网址是http://example.com?id1=100&text=my%20text

console.log(getURLParameter('id1')); // 100
console.log(getURLParameter('text')); // "my text"