从 URL 中提取变量并将其设置为文本框的值

Jor*_*vis 0 html javascript

我有以下 URL:http://localhost:8888/datatest?username=JD042719 我想拉入"JD042719". 此问题不需要“获取”请求。然后,用户名值应设置为另一个文本框的值。也许是这样的:

超文本标记语言

<label for="Assoc">Associate ID</label>
<input type="text" name="AssocID" id="AssocID" required="required">
Run Code Online (Sandbox Code Playgroud)

JavaScript

$(function associd(){
document.getElementById("AssocID").value=username;
});
Run Code Online (Sandbox Code Playgroud)

FWD*_*ker 5

新答案(2021)

下面的答案已经非常过时了。除非您需要支持 Internet Explorer,否则您应该只使用URLSearchParams,如下所示:

var username = (new URLSearchParams(window.location.search)).get("username");
Run Code Online (Sandbox Code Playgroud)

旧答案(2015)

使用此答案中提供的优秀功能,如下所示:

用法

var username = getParameterByName("username");
Run Code Online (Sandbox Code Playgroud)

功能

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Run Code Online (Sandbox Code Playgroud)

该变量username现在应该保存该值JD042719(或 URL 中的任何值)。