动态发送表单

时间:2014-01-14 22:11:56

标签: javascript jquery forms post

This is the link that i'm working with

我正在尝试避免使用form.submit来购买该商品。用户单击该项目,然后必须确认购买。它实际上不是一个发送的表单,而是运行一个函数shown here。您可以使用复制并粘贴字符串并使用control + F来执行保存函数的脚本部分:(;// pages/PurchaseConfirmationModal.js

我查了POST方法,但我无法弄清楚如何让它工作;

$.post("Form here", // How to identify the form?
    function( data ) {
       // how do I send the data?
    }
);

2 个答案:

答案 0 :(得分:1)

在表单id:s中输入输入字段,然后您可以获取它们的值以便为$ .post传递它,例如

<input type="text" id="input_one"/>
<input type="text" id="input_two"/>

然后:

var post_data={
    first_value: $("#input_one").val(),
    second_value: $("#input_two").val()
};

$.post("http://...",post_data,
    function(data) {
        // Handle the response from the server here.
    }
);

答案 1 :(得分:0)

HTML PART

<form>
    <input type="text" value="" name="first_value" id="first_value" />
    <input type="text" value="" name="second_value" id="second_value" />

    <button id="submitForm" >Submit</button>
</form>

AJAX部分 单击按钮调用该功能。 然后使用$("input[id=first_value]").val()$("#first_value").val()向您收集表单数据。

$('#submitForm').click(function(event){     
    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)
    var formData = {    
            'first'             :   $("input[id=first_value]").val(),
            'second'            :   $("input[id=first_value]").val(),   
    };


    // process the form
    var ajaxResponse = $.ajax({
                                type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
                                url         : 'someURL', // the url where we want to POST
                                data        : JSON.stringify( formData ),
                                contentType :'application/json',
                                error       : function(data,status,error){
                                                console.log(data+': '+status+': '+error);
                                                },
                                success     :  function(status) {
                                                    //DO something when the function is successful
                                                }       
                    }).done(function(apiResponse) {
                            //Do something when you are done
                    });

});