如何不使用表格提交单个输入字段 [英] How to submit individual input field without form

查看:31
本文介绍了如何不使用表格提交单个输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我一直在写一些与页面交互的Javascript.作为其中一部分,我需要能够提交HTML输入字段.

Recently, I've been writing some Javascript that interacts with a page. As a part of this, I need to be able to submit an HTML input field.

从我所看到的来看,大多数时间输入字段都是其自身形式的一部分.例如,StackOverflow的搜索栏的形式为搜索",输入字段为"q".

From what I've seen, most of the time input fields are a part of their own form. For example, StackOverflow's search bar has the form "search" and input field "q".

但是,在我正在使用输入字段的特定页面上,它没有自己的形式.它只是包含页面许多部分的更大形式的一部分.

However, on the particular page that I'm working with the input field does NOT have its own form. It is only a part of a greater form that encompasses many sections of the page.

我知道您可以通过调用表单上的.submit()方法来提交表单.但是,这似乎不适用于单个输入字段.

I'm aware that you can submit forms by calling the .submit( ) method on the form. However, this does not appear to work for individual input fields.

我知道此输入字段可以单独提交,因为当您手动键入文本并按Enter时,它可以工作.输入字段没有问题,可以轻松更改其值.

I know that this input field can be submitted individually, because when you manually type text and press Enter it works. I have no issues with the input field, and I can easily change its value.

基本上,我的问题归结为:

Basically, what my question boils down to is:

如何在不调用form.submit()的情况下提交单个输入字段?

How can I submit an individual input field without calling form.submit( )?

推荐答案

您可以使用jquery轻松发布帖子.

You can make a post pretty easily with jquery.

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
            $(document).ready(function() {

                $('#btnSubmit').click(function() {
                    var inputVal = $('#inputField').val();
                    $.ajax
                    ({
                        type: "POST",
                        url: 'your_url_for_handling_post',
                        contentType: "application/json",
                        data: JSON.stringify({"Username":inputVal})
                    })
                    .done(function(data) {
                        console.log(data);
                    });
                });
            });
        </script>

    </head>
    <body>
        <input type='text' id='inputField' name='username' />
        <input type='submit' id='btnSubmit' value='Submit' />

        <!-- you can use any element to trigger the submit
        <div id='btnSubmit'>Submit</div>
        -->
    </body>
</html>

json不是必需的.我只是把它放在那里,因为那是我通常的做法.您绝对可以自行发送值.

json is not a requirement. I just put that in there because that's how I normally do it. You can definitely just send the value by itself.

这篇关于如何不使用表格提交单个输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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