用户输入URL

user input to URL

本文关键字:URL 输入 用户      更新时间:2023-09-26

我有一些url,我需要用输入type="text"中的用户输入来替换其中的一些部分,然后点击按钮移动到新的链接
如何在URL中放置变量?

//一些url/trends.cgi?createimage&t1=14122757517&t2=1412843917&假设初始状态=是&assumestatesdurignotrunning=yes&initializamedhoststate=0&initializamedservicestate=0&假设保留=是&includesoftstates=no&主机=SCP-3&service=MODIFICATION+TIME+EDR+FILES&回溯=4&缩放=4

我有函数,但它把输入放在url的末尾。

function redirect() {
    var baseUrl = 'http://google.com.ua/';
    document.myform.action=baseUrl + document.getElementById('url').value;
}
<form name="myform" method="post" onsubmit="redirect()">
    <input type="text" id="url">
    <input type="submit" value="submit">
</form>

您可以构建手动查询字符串解析器和构造函数,示例如下:

function parseQuery(qstr){
    var query = {};
    var a = qstr.split('&'); //take the passed query string and split it on &, creating an array of each value
    for (var i in a) { //iterate the array of values
        var b = a[i].split('='); //separate the key and value pair
        query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]); //call decodeURIComponent to sanitize the query string
    }
    return query; //returned the parsed query string object
}
function buildQuery(obj){
    var str = [];
    for(var p in obj) //iterate the query object
       if (obj.hasOwnProperty(p)) { //check if the object has the propery name we're iterating
           str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); //push the encoded key value pair from the object into  the string array
       }
    return str.join("&"); //take the array of key value pairs and join them on &
} 

下面我们取你给出的字符串,例如:

var $str = 'createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4';

现在我们在字符串上调用parseQuery函数。

var obj = parseQuery($str);

然后我们迭代从parseQuery函数生成的对象

Object.keys(obj).forEach(function(k, i) {
    switch(k){
        case 't1':
            obj[k] = 'replacedt1';
            break;
        case 'service':
            obj[k] = 'replacedServices';
            break;
        case 'host':
            obj[k] = 'replacedHost';
    }         
});

现在obj变量具有新更新的值。我们可以使用buildQuery函数通过在.中传递对象来重建查询

console.log(buildQuery(obj));

这将产生类似的东西:

createimage=undefined&t1=replacedt1&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=replacedHost&service=replacedServices&backtrack=4&zoom=4 

像往常一样,jsFiddle

您可以使用新的URL对象(对于较旧的浏览器,有一个polyfill):

var url = new URL("http://some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4");
url.searchParams.set("t1", "someNewT1");
url.searchParams.set("t2", "someNewT2");
url.searchParams.set("host", "someNewHost");
url.searchParams.set("service", "someNewService");
alert(url.href);
/*
http://some-url/trends.cgi?host=someNewHost&assumestateretention=yes&initialassumedservicestate=0&t2=someNewT2&initialassumedhoststate=0&assumeinitialstates=yes&zoom=4&backtrack=4&createimage=&assumestatesduringnotrunning=yes&includesoftstates=no&service=someNewService&t1=someNewT1
*/

用JavaScript玩了一点,我相信这解决了你的问题:http://jsfiddle.net/dk48vwz7/

var linktext = "http://site/some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4";
//we'll use an in-memory "hyperlink" object for basic parsing
var anchor = document.createElement("A");
anchor.href=linktext;
//the query string starts with ?, we remove it. 
//then, split it by & symbol
var queryvars = anchor.search.replace(/^'?/, '').split('&');
//now looping through all parts of query string, creating an object in form key->value
var querycontent = {};
for( i = 0; i < queryvars.length; i++ ) {
    var queryvar = queryvars[i].split('=');
    querycontent[queryvar[0]] = queryvar[1];
}
//this allows us to reference parts of the query as properties of "querycontent" variable
querycontent.service = "AnotherService"
//TODO: change the properties you actually need
//and now putting it all back together
var querymerged = [];
var g = "";
for (var key in querycontent){
    var fragment = key;
    if (querycontent[key]) {
        fragment += "=" + querycontent[key];
    }
    querymerged.push(fragment);
}
anchor.search = querymerged.join("&")
//finally, access the `href` property of anchor to get the link you need
document.getElementById("test").innerText=anchor.href;