使用JQuery通过Ajax以Json格式发送表单数据

时间:2013-11-26 20:55:53

标签: jquery ajax

标题说我正在通过ajax发送一些帖子数据。但我一直在收到错误,有人可以看看代码并解释为什么我的ajax调用会一直失败吗?

submitForm(jQuery('#priceCalc'), {name: 'thingdoto', value: "true"});

function submitForm(form, data) {
        var postData = form.serializeArray(),
            formURL = form.attr("action");

        postData.push(data);
        console.log(postData);
        jQuery.ajax({
                url : formURL,
                type: 'POST',
                dataType : "json",
                data: postData,
                success:function(data)
                {
                        jQuery('#priceTotal').html(data);
                },
                error: function()
                {
                        jQuery('#priceTotal').html('error');
                }
        });
}

编辑:ajax调用返回错误,因此它没有成功。不知道为什么。

2 个答案:

答案 0 :(得分:11)

您将数据作为数组发送,而不是JSON字符串。

你想做这样的事情。

$("form#ID").submit(function(e){

    e.preventDefault();

    var data = {}
    var Form = this;

    //Gathering the Data
    //and removing undefined keys(buttons)
    $.each(this.elements, function(i, v){
            var input = $(v);
        data[input.attr("name")] = input.val();
        delete data["undefined"];
    });

    //Form Validation goes here....

    //Save Form Data........
    $.ajax({
        cache: false,
        url : ?,
        type: "POST",
        dataType : "json",
        data : JSON.stringify(data),
        context : Form,
        success : function(callback){
            //Where $(this) => context == FORM
            console.log(JSON.parse(callback));
            $(this).html("Success!");
        },
        error : function(){
            $(this).html("Error!");
        }
    });

答案 1 :(得分:0)

老问题,但我遇到了这种情况:

jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK

并且发现问题(在我的情况下)是从button内部form调用ajax发送JSON似乎导致JQuery误解服务器响应 - 并且总是考虑它一个错误。我的解决方案是将form更改为div或将button标记更改为a标记(使用Bootstrap渲染为按钮)

这有效

<div>
    <button></button>
</div>

<form>
    <a></a>
</form>
相关问题