将JSON对象作为表单数组发送

时间:2014-02-07 11:51:20

标签: javascript ajax arrays json

我需要将一些数据发布到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字符串发送。

3 个答案:

答案 0 :(得分: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("&");

答案 1 :(得分: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 + "...");

当然,这段代码还没有准备就绪。只是一个例子。

答案 2 :(得分: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
            });