【问题标题】:Send Post Form Data in Json Format Via Ajax With JQuery使用 JQuery 通过 Ajax 以 Json 格式发送表单数据
【发布时间】:2013-11-26 20:55:52
【问题描述】:

正如标题所说,我正在通过 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 调用返回错误,所以它没有成功。不知道为什么。

【问题讨论】:

  • 您知道,提及这些错误是什么很有用。
  • 哦,嘿!抱歉,它只是在 ajax 调用中返回错误,所以我只是字符串“error”。该函数不成功。
  • URL命中是否返回2xx
  • 您确定收到 200 响应吗?响应正文中有什么?它实际上是可解析的 JSON 吗?
  • 你能分享那个 JSON 块吗?或者至少通过 jsonlint.com 运行它,看看它是否有效?

标签: jquery ajax


【解决方案1】:

您将数据作为数组发送,而不是 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!");
        }
    });

【讨论】:

  • 此逻辑“收集数据”适用于文本字段,但不适用于复选框。无论复选框是否被选中,它总是传输复选框元素的“值”。
【解决方案2】:

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

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

发现问题(就我而言)是从form 内部的button 调用ajax 来发送JSON 似乎会导致JQuery 误解服务器响应——并且总是认为这是一个错误。我的解决方案是将form 更改为div 或将button 标记更改为a 标记(使用Bootstrap 呈现as 按钮)

成功了

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

<form>
    <a></a>
</form>

【讨论】:

    猜你喜欢
    • 2012-07-14
    • 2016-07-17
    • 2013-03-04
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多