在同一响应中返回多个JSON对象并对其进行解析

本文关键字:对象 JSON 响应 返回 | 更新日期: 2023-09-27 18:09:36

我有以下代码:(为便于阅读而简化)

c#

        foreach(DataRow dRow in myDS.Tables[0].Rows){
            Company myCompany = new Company();
            myCompany.id = int.Parse(dRow["id"].ToString());
            Companies.Add(myCompany);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        Response.Write(serializer.Serialize(Companies));
        Response.End();
jQuery

$.getJSON('ajax.aspx?what=' + $('input[name="what"]').val() + '&where=' + $('input[name="what"]').val(), function (data) {
    $.each(data, function (key, val) {
        var myCompany = new function () {
            this.id = val.id;
        }
        Companies.push(myCompany);
    });
});

现在,我在c#代码中有另一个对象,名为Cities我想在同样的请求中返回它。

比如

Response.Write(serializer.Serialize(Companies));
Response.Write(serializer.Serialize(Cities));
Response.End()

,当然在客户端解析它。

我怎么能做那样的事情呢?

在同一响应中返回多个JSON对象并对其进行解析

您可以将这两个属性包装成一个匿名对象:

var result = new { Cities = Cities, Companies = Companies };
Response.Write(serializer.Serialize(result);
Response.End();

或者如果你使用的是不支持匿名对象的旧。net版本,你可以定义一个包装器类:

public class Wrapper
{
    public IEnumerable<Cities> Cities { get; set; }
    public IEnumerable<Company> Companies { get; set; }
}

然后:

Wrapper result = new Wrapper();
wrapper.Cities = Cities;
wrapper.Companies = Companies;
Response.Write(serializer.Serialize(wrapper);
Response.End();

也修复你的AJAX调用,因为你没有正确的url编码你的参数:

var data = { 
    what: $('input[name="what"]').val(), 
    where: $('input[name="what"]').val() 
};
$.getJSON('ajax.aspx', data, function (data) {
    $.each(data.Companies, function (index, val) {
        var myCompany = new function () {
            this.id = val.id;
        }
        Companies.push(myCompany);
    });
});

您需要像这样创建包含两个集合的Object:

{
"Cities": { ... Cities Collection ... },
"Companies": { ... Companies Collection ... }
}

创建一个Object,比如

[Serializable]
public class Output {
    Collection<City> cities;
    Collection<Company> companies;
}

则将此对象与数据并输出