JS处理服务端Response回来的数组

最近在做一个项目时,需要在服务器端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来进行通信的。通信后,需要处理得到的结果信息。

View Code
<!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。



原文地址:https://www.cnblogs.com/oneivan/p/2420219.html