我一直使用PHP将查询字符串传递到表单中,但是我正在寻找一个静态站点方案,并且需要URL中的查询数据来填充表单字段。
我有没有控制台错误的代码,但是数据没有传递到表单字段中。有谁知道该怎么做才能在所有现代和旧版浏览器上正常工作?
function getQueryString() {
var result = {};
if(!window.location.search.length) return result;
var qs = window.location.search.slice(1);
var parts = qs.split("&");
for(var i=0, len=parts.length; i<len; i++) {
var tokens = parts[i].split("=");
result[tokens[0]] = decodeURIComponent(tokens[1]);
}
return result;
}
$(document).ready(function() {
$("#theForm").submit(function(e) {
//var that = this;
var qs = getQueryString();
for(var key in qs) {
var field = $(document.createElement("input"));
field.attr("name", key).attr("type","hidden");
field.val(qs[key]);
$(this).append(field);
}
});
});
https://formpopulate.netlify.com/index.html?name=john&email=john@aol.com https://formpopulate.netlify.com/
答案 0 :(得分:0)
您应该使用URL seachParams:
var params = (new URL("https://example.com/?name=Jonathan&age=18&test=a%20long%20string")).searchParams;
var name = params.get("name"); console.log(name); // is the string "Jonathan"
var age = parseInt(params.get("age")); console.log(age);// is the number 18
var test = params.get("test"); console.log(test); // is a long string