[英]Send JSON object as a form array
我需要將一些數據發布到URL。 我需要得到我的對象:
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字符串發送。
循環遍歷對象,將每個屬性及其值轉換為鍵值對。
由於您的其他要求,您需要使用profile[
和]
包裝每個鍵。
然后在它們之間添加&
。
var data = [];
for (var prop in profile) {
if (profile.hasOwnProperty(prop) {
data.push(encodeURIComponent("profile[" + prop + "]") + "=" + encodeURIComponent(profile[prop]);
}
}
var urlencoded = data.join("&");
你是說下面的嗎?
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 + "...");
當然,此代碼尚未准備就緒。 只是一個例子。
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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.