2011-04-05 45 views
1

我试图查询包含关于“票”使用jQuery's .ajax()方法信息的数据库...自定义HTTP响应,C#和.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等来访问不同的字段?

+0

是否有可能使用任何java scrip库? json在这里是一个很好的关键词。否则,将数据转换为xml,将其作为文本发送并解析到客户端。 – user492238 2011-04-05 14:16:00

回答

3

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

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

+0

@archil ... 1.此链接不起作用。 2.你能提供一个建立这种回应的例子吗? – Hristo 2011-04-05 14:22:48

+0

查看http://api.jquery.com/jQuery.parseJSON/。 – StuperUser 2011-04-05 14:24:03

+0

@StuperUser ...我并不很担心在客户端解析。我想弄清楚如何首先创建响应,然后担心解析它。如果我不必解析它,那就更好了,但我想先把它搞清楚。 – Hristo 2011-04-05 14:27:21

1

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

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

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

否则,你可以通过你的数组列表循环,并自己建立逗号分隔列表。那么你可以解析js中的逗号分隔值。

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

+0

是啊...我不想做任何解析。应该有一种方法可以将它作为Object返回,就像我要使用JSON一样。不过,我现在要避免使用JSON ......有没有办法在没有外部库的情况下执行此操作? – Hristo 2011-04-05 14:21:56

+0

@Hristo - 不,你正在穿越应用程序界限,所以序列化是必要的。 JSon和XML是您的标准序列化选项。当数据到达客户端时,你想要做什么?另一种选择是在服务器上呈现所需的html并返回该html,然后使用jquery将结果放在所需的页面上。那将是最快最简单的解决方案。 – NerdFury 2011-04-05 14:34:39

+0

@NerdFury ... gotcha。你是完全正确的。我将使用JSON解决方案。我只是试图从数据库中查询一行,并使用该行的字段来显示信息。 – Hristo 2011-04-05 14:38:54