2012-09-20 193 views
0

如何將JSON格式的數據發送到AJAX POST請求。 我的數據由一個JAVA人員對象組成,這個對象有很多屬性,比如姓名,dob,地址,電話等等, 供應商列表(供應商名稱,編號)給這個人,另一個助手名稱(助手名稱,編號)。 如何將所有數據合併到一個JSON對象中,並使用jQuery.post(url,data)發送它?如何在Ajax post請求中發送不同的JSON數據

+0

建立你發送的數據 –

+0

之前你的數據對象做我必須手動構建呢? var mydata = {person:jack,dob:1980-09-9,address:address}等等?我正在尋找一種更簡單的方法來做到這一點,如果有的話。 – Sapphire

回答

0

你可以建立一個複雜的JSON對象和提交到服務器。

var employees = { "accounting" : [ // accounting is an array in employees. 
           { "firstName" : "John", // First element 
            "lastName" : "Doe", 
            "age"  : 23 }, 

           { "firstName" : "Mary", // Second Element 
            "lastName" : "Smith", 
            "age"  : 32 } 
           ], // End "accounting" array.         
       "sales"  : [ // Sales is another array in employees. 
           { "firstName" : "Sally", // First Element 
            "lastName" : "Green", 
            "age"  : 27 }, 

           { "firstName" : "Jim", // Second Element 
            "lastName" : "Galley", 
            "age"  : 41 } 
           ] // End "sales" Array. 
      } // End Employees 

此處瞭解詳情:JSON Examples

-1

嘗試JSON API ...

var person = JSON.stringify(
[{ 
    name:"dob johnson", 
    address:"somewhere over the rainbow", 
    phone:"+357 99798342" 
    },{ 
    name:"john Doe", 
    address:"4th barrel street", 
    phone:"+357 927124442" 
    }] 
); 
person = JSON.stringify(person); 

然後將其發送到服務器

$.ajax({ 
    type: 'POST', 
    url: url, 
    data: {json:encodeURIComponent(person)}, 
    success: success, 
    dataType: dataType 
}); 

服務器端就

// Decode ... $_POST['json'] 
jsonString = urldecode($_POST['json']); 
+0

好的,但我也有一個供應商和幫手類型。 – Sapphire

+0

我只有一個「人」和多個「供應商」和「幫手」。我需要將所有信息合併併發送到服務器。 – Sapphire

+0

@Sapphire:所以,只需將這些添加到對象。你有什麼問題? –

相關問題