【问题标题】:custom HTTP Response, C# and .ajax()?自定义 HTTP 响应、C# 和 .ajax()?
【发布时间】:2011-04-05 14:10:37
【问题描述】:

我正在尝试使用jQuery's .ajax() 方法查询包含“票证”信息的数据库...

$.ajax({
    type: 'GET',
    url: 'Preview.ashx',
    data: 'ticketID=' + ticketID,
    success: function (data) {

        // 'data' should be a row from the database, so it should be like an
        // array that contains each column of the row
        // do stuff with this data
    }
});

...所以一切正常。我在使用 data 变量时遇到问题。在服务器端,我确实...

// get the ticket ID from the POST parameter
int ticketID = context.Request["ticketID"] != null ? Convert.ToInt32(context.Request["ticketID"]) : -1;
if (ticketID >= 0) {

    // grab the data from the database, getInfo() will retrieve the row
    // in the DB that corresponds to the ticket ID given, returning an 
    // ArrayList with all of the information
    ArrayList theTicket = getInfo(context, ticketID);

    // now, I need to somehow return this information so that I could deal with it
    // in the 'success' callback function above
    return;
} else {

    // something went wrong with the 'newTicket' POST parameter
    context.Response.ContentType = "text/plain";
    context.Response.Write("Error with 'ticketID' POST parameter. \n");
    return;
}
return;

我已经对此进行了足够的调试,以确保 ArrayList 包含正确的信息。现在我只需要退货。

我该怎么做?我将如何返回 ArrayList 中的数据?是否可以构造响应以便我可以在回调函数中执行data.IDdata.otherColumnName 等...以访问不同的字段?

【问题讨论】:

  • 是否可以使用任何 java 脚本库? json 将是一个很好的关键字。如果没有,将数据转成xml,以文本形式发送,在客户端解析。

标签: c# asp.net ajax json httpresponse


【解决方案1】:

是的,这是可能的。看看JSON。您可以使用 JavascriptSerializerDataContractJsonSerializer 类以 JSON 格式序列化对象。也可以看看this link

您可以使用 ContentType application/json 和 body 将是上述序列化程序之一将返回的字符串。您可以使用与 else 语句中相同的代码

【讨论】:

  • @archil... 1. this link 不起作用。 2. 你能提供一个构建这样一个响应的例子吗?
  • @StuperUser... 我还不太担心在客户端进行解析。我想先弄清楚如何创建响应,然后再担心解析它。如果我不必解析它,那就更好了,但我想先启动并运行它。
  • 我编辑了我的答案。请参阅第二段和链接。情况与您的 else 语句相同,您需要内容类型和响应文本。
【解决方案2】:

您已经使用 Response.Write 在下面做正确的事情。

我会更改 GetInfo 以返回一个字符串数组,然后使用 String.Join。

string[] theTicket = getInfo(context, ticketId);
Response.Write(String.Join(",", theTicket);

否则,您可以遍历您的数组列表并自己构建逗号分隔列表。那么就可以解析js中的逗号分隔值了。

更好的选择是使用 json 库并将 ArrayList 序列化为 json 并在客户端使用。

【讨论】:

  • 是的...我不想做任何解析。应该有一种方法可以将它作为对象返回,就像我使用 JSON 一样。但是,我现在想避免使用 JSON……有没有办法在没有外部库的情况下做到这一点?
  • @Hristo - 不。您正在跨越应用程序边界,因此需要序列化。 JSON 和 XML 是您的标准序列化选项。当数据到达客户端时,你想对它做什么?另一种选择是在服务器上呈现您想要的 html 并返回它,然后使用 jquery 将结果放在您想要的页面上。这将是最快和最简单的解决方案。
  • @NerdFury... 明白了。你完全正确。我将使用 JSON 解决方案。我只是想从数据库中查询一行并使用该行的字段来显示信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
  • 2019-08-18
相关资源
最近更新 更多