Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将JSON对象作为表单数组发送_Javascript_Ajax_Arrays_Json - Fatal编程技术网

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

Javascript 将JSON对象作为表单数组发送,javascript,ajax,arrays,json,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, }; 像表单一

我需要将一些数据发布到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    application/x-www-form-urlencoded; charset=utf-8

出于某种原因,我不知道如何将其作为表单数组而不是JSON字符串发送

在对象上循环,将每个属性及其值转换为键值对

由于您的额外要求,您需要使用
配置文件[
]
包装每个键

然后在它们之间添加
&

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

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

你是在用jquery发送吗?@VladIoffe nope正在用网络客户端开发一个钛合金应用程序——为什么不使用json字符串呢?根据所使用的序列化程序,在服务器端将其反序列化为字典或键值对列表非常容易。
 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
            });