我有一个带有表单的HTML页面,该表单仅包含一个字段.提交实际上并不会刷新页面,而是会进行本地JavaScript处理.
I have an HTML page with a form, containing only one field. The submit doesn't actually do a page refresh, but rather does local JavaScript processing.
这很好用,但是有一个缺点:您不能给某人提供预先提交格式的网址(例如example/myform?field=val).
This works great, but has one downside: you can't give someone a URL with the form presubmitted (e.g. example/myform?field=val).
如何在加载时告诉jQuery,如果URL包含?field=[val],则用val填充field,然后执行JavaScript提交操作?
How can I tell jQuery that, on load, if the URL contains ?field=[val], to fill field with val and then do the submit JavaScript action?
(如果您也可以反向执行此操作,则奖励点:提交时,将位置栏中的URL从example/myform更改为example/myform?field=[val],而无需进行页面刷新)
(Bonus points if you can do this in reverse as well: when you submit, change the URL in the location bar from example/myform to example/myform?field=[val], without doing a page refresh)
推荐答案未经测试,但也许是这样的:
Untested, but maybe something like this:
// 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函数.
Also see here for a starting point on possible getUrlParams function.
更多推荐
从URL填写表格
发布评论