繁体   English   中英

存储和输出表单数据

[英]Storing and outputting form data

我正在创建一个URL-Shortener,但是在获取jquery表单值方面存在一些问题,因此我可以输出缩短的URL文本。

是我正在使用的表单:

<form name="urlForm">
    <input type="text" name="url">
    <button id="submit" type="button">Submit</button>
    <p>Result:
        <!-- Output area. -->
        <span id="url-output"></span>   </p>
</form>

是我用来处理表单数据的JavaScript:

 // receive the form when "submit" button is clicked
    $('form[name=urlForm]').submit(function (event) {
        console.log('form submitted');
        // get the data in the form
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            //element[attribute=value]
            'name': $('input[name=url]').val(),
        };
    // process the form
    $.ajax({
        type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url: '/createShorter', // the url where we want to POST
        data: formData, // our data object
        dataType: 'json', // what type of data do we expect back from the server
        encode: true
    })

        // using the done promise callback
        .done(function (data) {
            // log data to the console so we can see
            console.log(data);

            // here we will handle errors and validation messages
        });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});

我认为问题在于我如何收集formData变量中的数据。 但是,尽管查看了文档和几个不同的尝试,我所做的一切似乎都没有输出任何相关的值。 我采取了不好的做法吗?

如何解析我需要的信息?

Snippet无法运行(严格的安全性),请查看PLUNKER Plunker演示了使用正确的表单,使用普通的JavaScript XMLHttpRequest() ,发布到真正的测试服务器并接收响应的json。 详细信息在Snippet中进行了注释。

SNIPPET(无功能)

 <!DOCTYPE html> <html> <head> </head> <body> <!--Use id and name, although name isn't used in this instance, it can be useful under different circumstances--> <form id='urlForm' name="urlForm"> <input type="text" id='url' name="url"> <!--Use an input type submit button instead, it will automatically trigger a submit event once clicked--> <input id="submit" type="submit"> <br/> <label>Result: <!--Using a real output element allows you to display data with the value property or with content methods such as innerHTML or textContent--> <output id="urlOutput"></output> </label> </form> <script> // Reference the form var f1 = document.getElementById('urlForm'); // Reference the output var o1 = document.getElementById('urlOutput'); // When a submit event is triggered... f1.onsubmit = function(e) { // Prevent the form from submitting normally e.preventDefault(); // reference a XHR object var req = new XMLHttpRequest(); // POST to server req.open('POST', 'http://httpbin.org/post', false); // reference a FormData object var formData = new FormData(f1); req.send(formData); o1.value = req.response; } </script> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM