发送POST表单数据以JSON格式通过Ajax使用jQuery [英] Send Post Form Data in Json Format Via Ajax With JQuery

查看:726
本文介绍了发送POST表单数据以JSON格式通过Ajax使用jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我通过AJAX发送一些POST数据。但我一直收到错误,任何人都可以看看在code,并解释为什么我的ajax调用保持失败?

as the title says I'm sending some post data via ajax. but I keep on getting errors, can anyone take a look at the code and explain why my ajax call keeps failing?

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调用返回错误,所以它只是没有成功。不知道为什么。

The ajax call returns the error, so it's just not succeeding. Don't know why.

推荐答案

您发送的数据为一个数组,而不是一个JSON字符串。

Your Sending data as an Array, not a JSON string.

您想要做这样的事情。

$("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!");
        }
    });

这篇关于发送POST表单数据以JSON格式通过Ajax使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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