我有一个带有表单的HTML页面,只包含一个字段。提交实际上并不进行页面刷新,而是进行本地JavaScript处理。
这很有用,但有一个缺点:你不能给某人一个预先提交表格的网址(例如http://example.com/myform?field=val
)。
我如何告诉jQuery在加载时,如果网址包含?field=[val]
,用field
填充val
,然后执行提交JavaScript操作?
(如果您也可以反向执行此操作:当您提交时,请将位置栏中的网址从http://example.com/myform
更改为http://example.com/myform?field=[val]
,而不进行页面刷新)
答案 0 :(得分:1)
未经测试,但可能是这样的:
// Setup a document ready to run on initial load
$(document).ready(function() {
var urlParams = getUrlParams()
, form;
// Only proceed if there are URL params
// Note this assumes that all URL params are valid input fields in your form, that they have been decoded, and that all the fields you need are there. Adjust accordingly.
if (urlParams) {
form = $('#your_form');
$.each(urlParams, function(field, value) {
form.find('input[name="' + field + '"]').val(value);
});
// Trigger your event listener
form.submit();
}
});
另请参阅此处了解可能getUrlParams function的起点。
答案 1 :(得分:0)
我有一个答案。
$(document).ready(function(){
var r = /[?|&](\w+)=(\w+)+/g; //matches against a kv pair a=b
var query = r.exec(window.location.href); //gets the first query from the url
while (query != null) {
//index 0=whole match, index 1=first group(key) index 2=second group(value)
$("input[name="+ query[1] +"]").attr("value",query[2]);
query = r.exec(window.location.href); //repeats to get next capture
}
//handles when someone clicks a input button with id submit
$('#submit').click(function(){
var url = window.location.pathname + "?";
$("input[name]").each(function(){
if (this.value) //if the forms have values
url += $(this).attr('name') + "=" + this.value + "&"; //appends the name and value
});
history.replaceState("hstory", "", url.substring(0, url.length - 1)); //changes the url without reloading and removes last &
});
});
第一部分处理从url获取值并将它们插入到表单输入中,而第二部分处理当一个人点击id为submit的按钮时将值重新加载到url中。