通过Ajax发送多个JSON对象

通过Ajax发送多个JSON对象

问题描述:

我想通过Ajax发送多个JSON对象。通过Ajax发送多个JSON对象

我的对象(从多个表单创建)如下;

当Ajax发送JSON时它是空的。但是,如果我搜索任何一个json对象,它包含值。我认为这个问题似乎是当我创建多层对象。

我还需要了解如何访问我的控制器中的对象。

它会是什么样的:data.dataFormOne.title

var dataFormOne = ''; 
var dataFormTwo = ''; 
var dataFormThree = ''; 

$("#formone").submit(function(e){ 
    var title = $('select[name="Title"]').val();  
    dataFormOne = {firstname: firstname}; 
});     

$("#formtwo").submit(function(e){ 
    var address = $("#address").val();;  
    dataFormTwo = {address: address}; 
});         

$("#formtwo").submit(function(e){ 
    var country = $("#country").val();; 
    dataFormThree = {country: country}; 
});       

function sendData() { 
    var data = { 
    formone: dataFormOne, 
    formtwo: dataFormTwo, 
    formThree: dataFormThree, 
    }; 

    $.ajax({ 
    type: "POST", 
    url:URL, 
    dataType: "json", 
    data: data , 
    cache: false, 
    success: function (data) { 
     if (data.result) { 
     console.log(data.result); 
     } else { 
     alert("There has been an error\nPlease make sure you are logged in."); 
     } 
    }, 
    complete: function() {} 
    });     
} 
+0

1.代码中有两个'#formtwo' ..它不应该是一个吗? 2.在提交回调函数中,你在调用'sendData'函数吗? – Santosh

传统设置为true,在你的Ajax配置 并发送类似这样的

traditional : true, 
data:{formone: dataFormOne,formtwo: dataFormTwo,formThree: dataFormThree} 
+0

嗨哈桑。我尝试过这个。它没有工作 –

+0

你得到什么错误? –

我创建从你的问题的示例代码。有几件事情你不知道(比如每次提交时都没有调用sendData),单个页面上的多个表单也不是“允许的”(尽管如此,你仍然可以使用它)。数据对象也被重新格式化。一旦您在控制器上收到该对象,您将可以轻松搜索所需的字段。

一旦运行这个例子来看看在控制台的东西会被发回到你的控制器的例子(你需要取消对阿贾克斯后回叫,使其工作)

工作小提琴:https://jsfiddle.net/HappyiPhone/wfkggtzm/1/

var dataFormOne =''; var dataFormTwo =''; var dataFormThree ='';

$("#formone").submit(function(e){ 
      dataFormOne  = {firstname: firstname}; 
      sendData(e); 
     });     

      $("#formtwo").submit(function(e){ 
      var address = $("#address").val();;  
           console.log($("#formtwo").serialize()); 
      dataFormTwo  = {address: address}; 
      sendData(e); 
     });         

      $("#formtwo").submit(function(e){ 
      var country = $("#country").val();;  
      dataFormThree  = {country: country}; 
      sendData(e); 
     });       



     function sendData(e) { 

      var data  = {dataFormOne, 
          dataFormTwo, 
          dataFormThree, 
          }; 
        console.dir(data); 
     e.preventDefault(); 
     /* 
     $.ajax({ 
        type: "POST", 
        url:URL, 
        dataType: "json", 
        data: data , 
        cache: false, 
        success: function (data) 
        { 
         if (data.result) 
         { 
         console.log(data.result); 
         } 
         else 
         { 
          alert("There has been an error\nPlease make sure you are logged in."); 
         } 
        }, 
        complete: function() {} 
       });     

       */ 
}