【问题标题】:Send JSON object as a form array将 JSON 对象作为表单数组发送
【发布时间】:2014-02-07 11:51:20
【问题描述】:

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

【问题讨论】:

  • 你是用jquery发送的吗?
  • @VladIoffe nope 使用网络客户端开发钛应用程序 - docs.appcelerator.com/titanium/latest/#!/api/…
  • 为什么不使用 json 字符串?根据您使用的序列化程序,很容易将其反序列化为服务器端的 Dictionary 或键值对列表。

标签: javascript ajax arrays json


【解决方案1】:

循环遍历对象,将每个属性及其值转换为键值对。

由于您的额外要求,您需要使用 profile[] 包装每个密钥。

然后在它们之间添加&

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

【讨论】:

    【解决方案2】:

    你的意思是下面的吗?

    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 + "...");
    

    当然,这段代码还没有准备好生产。只是一个例子。

    【讨论】:

      【解决方案3】:
       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
                  });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-12
        • 2023-04-08
        • 1970-01-01
        • 2021-01-26
        • 2013-02-09
        • 1970-01-01
        • 2017-10-01
        • 2017-04-27
        相关资源
        最近更新 更多