遍历JSON对象以在jQuery中向FormData添加值

时间:2019-02-18 06:33:13

标签: jquery json ajax

我在jquery中有一个JSON对象,如下所示:-

promotions

我必须将带有multipart / form-data的POST请求发送到服务器。我创建了一个FormData对象:-

category

我需要做的是遍历JSON中的每个元素,并将它们附加到我的变量fd中。这就是我想要的:-

id

有什么想法要实现吗?

5 个答案:

答案 0 :(得分:1)

您可以使用for

迭代对象
for (var key in userObj) {
  fd.append(key, userObj[key]);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

答案 1 :(得分:1)

您可以这样做:

let userObj = { 
 "loginId":"abc123", 
 "class":"5", 
 "email":"akhil.gts1997@gmail.com", 
 "level":"1"
};

let fd = new FormData();

for (let key in userObj){
    fd.append(key, userObj[key])
}

答案 2 :(得分:1)

git commit

答案 3 :(得分:1)

var userObj =
{ 
 "loginId":"abc123", 
 "class":"5", 
 "email":"akhil.gts1997@gmail.com", 
 "level":"1"
}
var fd = new FormData(); 
$.each(userObj, function(i, val) {
  console.log(i + " " + val);
  fd.append(i, val);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

Try something like this.

答案 4 :(得分:0)

let userObj = { 
 "loginId":"abc123", 
 "class":"5", 
 "email":"akhil.gts1997@gmail.com", 
 "level":"1"
};

var newdata= new FormData();

 $.each(userObj, function (key, value) {
    newdata.append(key, userObj[key]);
    console.log(key, userObj[key])
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>