2011-04-05 49 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