从URL填写表格 [英] Filling out a form from the URL

查看:157
本文介绍了从URL填写表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有表单的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.

这很好用,但是有一个缺点:您不能给某人提供预先提交格式的网址(例如http://example.com/myform?field=val).

This works great, but has one downside: you can't give someone a URL with the form presubmitted (e.g. http://example.com/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从http://example.com/myform更改为http://example.com/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 http://example.com/myform to http://example.com/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();
    }
});

另请参阅此处以获取关于

Also see here for a starting point on possible getUrlParams function.

这篇关于从URL填写表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆