2014-02-07 37 views
0

我需要將一些數據發佈到URL。我需要得到我的對象:將JSON對象作爲表單數組發送

var profile = { 
    firstname: first_name, 
    lastname: last_name, 
    email: email, 
    phone: phone, 
    mobile: mobile, 
    address_1: address_1, 
    address_2: address_2, 
    city: city, 
    postcode: postcode, 
}; 

發送到端點就像一個窗體。比如一個數組

profile[firstname] = "Billy" 
profile[lastname] = "Jones" 
... 

我的頭Content-Type

Content-Type application/x-www-form-urlencoded; charset=utf-8 

出於某種原因,我無法弄清楚如何將其發送的形式排列,而不是一個JSON字符串。

+0

是你使用jquery發送的嗎? – vlio20

+0

@VladIoffe nope使用網絡客戶端開發鈦應用程序 - http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.Network.HTTPClient – iamjonesy

+0

爲什麼不使用json字符串?根據所使用的序列化程序,將其去序列化爲服務器端的字典<字符串,對象>或鍵值對列表非常簡單。 –

回答

0

在對象上循環,將每個屬性及其值轉換爲鍵值對。

由於您的額外要求,您需要用profile[]來包裝每個密鑰。

然後在它們之間加上&

var data = []; 
for (var prop in profile) { 
    if (profile.hasOwnProperty(prop) { 
     data.push(encodeURIComponent("profile[" + prop + "]") + "=" + encodeURIComponent(profile[prop]); 
    } 
} 
var urlencoded = data.join("&"); 
0

你的意思是以下嗎?

var xhr = new XMLHttpRequest(); 
xhr.open("POST", url, true); 
xhr.setContentHeader("Content-type", "application/x-www-form-urlencoded"); 
xhr.onreadystatechange = function() { /* whatever */ }; 
xhr.send("firstname=" + firstname + "&lastname=" + lastname + "..."); 

當然,這段代碼不是生產準備好的。只是一個例子。

0
var profile = {}; 
    profile.firstname = first_name, 
    profile.lastname = last_name, 
    profile.email = email, 
    profile.phone = phone, 
    profile.mobile = mobile, 
    profile.address_1 = address_1, 
    profile.address_2 = address_2, 
    profile.city = city, 
    profile.postcode = postcode, 
     $.ajax({ 
       url: "url", 
       data: "{profile:" + JSON.stringify(profile) + "}", 
       type: "POST", 
       contentType: "application/json;charset=utf-8", 
       dataType: "json", 
       success: onSussess, 
       error: onError 
      });