DIV CSS 佈局教程網

ASP.NET 中的 AJAX 呼叫實作全解析
編輯:JQuery特效代碼     

一、前言

最近在 ASP.NET 中實作了一個 AJAX 呼叫流程:Client 端先從 ASP.NET 後台取得一個頁面模板,頁面初始化時再向 Server 索取相關資料,以實現模板的動態顯示。整體流程如下:

1) Client 向 ASP.NET 後台發送 HTTP GET 請求;

2) 後台回傳一個 HTML 模板,同時在記憶體中存一份 XML String(含動態顯示所需資料);

3) Client 初始化頁面時發送 AJAX 請求,取得 XML String;

4) 利用 XML String 客製化 HTML 模板,完成動態顯示。

二、關鍵點與程式碼

2.1 ASP.NET Server 端

用 C# 生成 XML String,可使用 System.Xml 命名空間下的類別:

. 代碼如下:

ArrayList steps = new ArrayList();
String errordiscription = "Not in position";
for (int i = 0; i < 5; i++)
{
steps.Add(new Step(@"images/1.jpg", "step21 description"));
}
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode rootNode = doc.CreateElement("Root");
doc.AppendChild(rootNode);
XmlNode errorNode = doc.CreateElement("ErrorDescription");
errorNode.AppendChild(doc.CreateTextNode(errordiscription));
rootNode.AppendChild(errorNode);
XmlNode productsNode = doc.CreateElement("Steps");
rootNode.AppendChild(productsNode);
for (int i = 0; i < steps.Count; i++)
{
XmlNode productNode = doc.CreateElement("step");
XmlAttribute productAttribute = doc.CreateAttribute("description");
productAttribute.Value = ((Step)steps[i]).description;
productNode.Attributes.Append(productAttribute);
productNode.AppendChild(doc.CreateTextNode(((Step)steps[i]).imagePath));
productsNode.AppendChild(productNode);
}
Global.Repairsteps= doc.InnerXml;

響應 Ajax 請求時,記得加上 Content-Type 標頭:

. 代碼如下:

Response.Clear();
Response.AddHeader("Content-Type", "text/xml");
Response.Write(Global.Repairsteps);
Response.End();

多個 Request 之間的資料共享,可以透過一個 Global 靜態物件來達成:

. 代碼如下:

public class Global
{
static string _repairsteps;
public static string Repairsteps
{
get { return _repairsteps; }
set { _repairsteps = value; }
}
}

2.2 Client 端

用 AJAX 取得 XML:

. 代碼如下:

$.ajax({
type: "GET",
url: "https://localhost:3153/WebSite2/",
cache: false,
dataType: "xml",
error:function(xhr, status, errorThrown) {
alert(errorThrown+'\n'+status+'\n'+xhr.statusText);
},
success: function(xml) {
// 在這裡處理透過 Ajax 取得的 xml
}});

動態插入 HTML List 元素時,與其拼接 HTML 字串(容易因引號而多出大量跳脫字元),不如善用 jQuery 建立元素的能力。當作參數傳給 $ 的內容包含 <tag ...> 時,jQuery 會把它當成建立新 DOM 元素,而非選擇器:

. 代碼如下:

$(xml).find("step").each(function(){
var stepimagepath=$(this).text();
var stepdescription=$(this).attr("description");
additem(stepimagepath, stepdescription);
});
function additem(stepimagepath, stepdescription){
$('.ad-thumbs ul').append(
$('<li>').append(
$('<a>').attr('href', stepimagepath).append(
$('<img>').attr('src', stepimagepath).attr('alt', stepdescription)
)));
}

三、總結

本文整理了在 ASP.NET 中使用 AJAX 可能碰到的幾個關鍵點:以 C# 生成 XML 流、AJAX 的 Server 端與 Client 端溝通、Global 變數共享資料,以及用較好的方式動態插入 HTML 元素。

四、參考

https://www.dotnetperls.com/global-variables-aspnet

https://api.jquery.com/jQuery/

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved