最近在做一個項目時,需要在服務器端response回來一個結果數組,然后在客戶端的瀏覽器通過JS處理。
GetResult.ashx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ResponseDemo
{
/// <summary>
/// GetResult 的摘要說明
/// </summary>
public class GetResult : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string[] result = new string[] { };
bool ok = true;
//do something
//.....
if (ok)
{
result = new string[] { "success", "true", "url", "http://localhost:80/" };
}
else
{
result = new string[] { "error","false"};
}
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
客戶端是通過XmlHttpRequest來進行通信的。通信后,需要處理得到的結果信息。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = show;
xhr.open("GET", "GetResult.ashx", true);
xhr.send(null);
function show() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response= "";
try {
response = eval("(" + xhr.responseText + ")");
} catch (e) {
alert("error");
}
document.write("xhr.responseText: "+ xhr.responseText + "<br/>eval response: "+ response);
}
}
}
</script>
</body>
</html>
很明顯,上面這樣是會catch到錯誤信息的,輸出的也是:
xhr.responseText: System.String[]
eval response:
eval() 函數可計算某個字符串,並執行其中的的 JavaScript 代碼,在其中再加對括號,是為了把里面需要處理的字符串當作一個整體,避免與上下文造成解析錯誤。
看到一些朋友說,可以把需要response的信息轉換成字符串,並用特殊符號分隔,用JS處理時再Split。這無疑也是一個辦法,但總覺得不是很方便。
然后,弄了個折中的辦法:在Server端,先把數組解析了。
//context.Response.Write(result);
string resultString = "[";
for (int i = 0; i < result.Length; i++)
{
resultString += "'" + result[i].ToString() + "',";
}
resultString = resultString.TrimEnd(',') + "]";
context.Response.Write(resultString);
JS端的代碼不用改變,就可以成功取得response回來的數組了。
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response= "";
try {
response = eval("(" + xhr.responseText + ")");
} catch (e) {
alert("error");
}
document.write("xhr.responseText: "+ xhr.responseText + "<br/>eval response: "+ response);
}
}
輸出結果:
xhr.responseText: ['success','true','url','http://localhost:80/']
eval response: success,true,url,http://localhost:80/
上面中,也可以通過response[i]訪問。
這樣簡單的使用,之前沒掌握技巧,也花費不少時間。Mark it。