[英]How do I convert this multi-dimentional associative array to json?
I have a loop that creates an associative array in js that I need to convert to json.我有一个循环在 js 中创建一个关联数组,我需要将其转换为 json。
Javascript: Javascript:
var guest = {};
var guests = {};
for(var i=0;i<2;i++){
var name = GetName();
var email = GetEmail();
guest = { 'Email': email, 'Name': name };
guests.push(guest);
}
End of the loop would give me, say:循环结束会给我说:
{
{'Email':"bob@zyz.com", 'Name':"Mr. Bob"},
{'Email':"tom@zyz.com", 'Name':"Mr. Tom"}
}
How can I convert this to JSON?如何将其转换为 JSON? (OK with small jquery plugin)
(可以用小 jquery 插件)
I need to pass this json array to my MVC 3 controller:我需要将此 json 数组传递给我的 MVC 3 controller:
[HttpPost]
public ActionResult AddGuests(List<SelectedGuest> guests){
}
public class SelectedGuest
{
public string Email { get; set; }
public string Name { get; set; }
}
Thanks for reading.谢谢阅读。
You need square brackets if you want to deal with arrays.如果要处理 arrays,则需要方括号。 In javascript there are really two artifacts: objects (
{}
) and arrays of objects ( []
) and the distinction is really important:在 javascript 中确实有两个工件:对象(
{}
)和对象的 arrays ( []
),区别非常重要:
var guest = { };
var guests = [ ];
for(var i = 0; i < 2; i++) {
var name = GetName();
var email = GetEmail();
guest = { 'Email': email, 'Name': name };
guests.push(guest);
}
Now that we have fixed your javascript let's use AJAX to send this guests
array to the AddGuests
controller action:现在我们已经修复了您的 javascript,让我们使用 AJAX 将此
guests
数组发送到AddGuests
controller 操作:
$.ajax({
url: '/SomeController/AddGuests',
data: JSON.stringify(guests),
type: 'POST',
contentType: 'application/json', // <-- Make sure to set the proper content type
success: function(result) {
// TODO: handle the results of the controller action
}
});
The JSON.stringify
method shown here is implemented in most modern browsers but for older browsers you might want to include the following script .此处显示的
JSON.stringify
方法已在大多数现代浏览器中实现,但对于较旧的浏览器,您可能需要包含以下脚本。
One last remark:最后一句话:
Never hardcode urls in javascript like this:永远不要像这样在 javascript 中硬编码网址:
url: '/SomeController/AddGuests'
Always use Url helpers in ASP.NET MVC when dealing with urls, like this:在处理 url 时,始终在 ASP.NET MVC 中使用 Url 助手,如下所示:
url: '@Url.Action("AddGuests", "SomeController")'
After your for loop call JSON.stringify();
在你的 for 循环调用
JSON.stringify();
var json = JSON.stringify(guests);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.