2013-11-26 82 views
3

作为标题说我通过ajax发送一些文章数据。但我不断收到错误,任何人都可以看看代码并解释为什么我的ajax调用会一直失败?发送表单数据JSON格式通过Ajax使用JQuery

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

+0

它的button标签更改为a标签你知道,有必要提一下这些错误是什么。 – alex

+0

哦,嘿!对不起,它只是返回错误,在ajax调用,所以我只是字符串“错误”。该功能不成功。 – Spittal

+0

是返回'2xx'的URL命中吗? – alex

回答

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 AJAX技术form内发送JSON似乎会导致JQuery误解服务器响应 - 并始终认为它是一个错误。我的解决办法是把form更改为div或(使用引导程序来呈现的按钮)

这个工作

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

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