网上介绍了几种方法如下:
假设在服务器端计算得到了一个数组s需要传递到JavaScript中的名为my_array的数组继续进行处理:
protected int[] s;//protected or public is required
为了测试给s赋几个值:
s = new int[100];
for (int i=0; i<s.Length; i++)
{
s[i] = i;
}
-------------------------------------------------------------------
方法一(ASP风格,不推荐):
In the aspx page:
<script language="javascript">
//将cs中的数组传js中的数组
var my_array = new Array(100);
<%
string iniArr = null;
for (int i=0; i<100; i++)
{
iniArr += "my_array[" + i + "]=" + s[i] + ";";
}
%>
<%=iniArr%>
//下面为测试用代码
for (i=0; i<100; i++)
{
document.all("num").innerText += my_array[i];  
}
</script>

-------------------------------------------------------------------
方法二(使用webservice,感谢bitsbird提供了代码):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
    <title>RealTime</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    <script language="javascript">
var intCallID=0;
function Init()
{
GetNewFeatured();
setInterval("GetNewFeatured()",10000);
}
function GetNewFeatured()
{
     Service.useService("http://localhost/WebService/LoadData/FeaturedService.asmx?WSDL","FeaturedService");
     intCallID=Service.FeaturedService.callService(RealTime_Result,"GetScores");
}
function RealTime_Result(result)
{
    if(result.error)
    {
     divFeatured.innerHTML=result.errorDetail.string;
    }
    else
    {
    divFeatured.innerHTML=result.value;
    }
}
</script>
</HEAD>
<body onload="Init()">
    <div id="Service" style="BEHAVIOR:url(webservice.htc)"></div>
    <div id="divFeatured"><FONT face="宋体"></FONT> </div>
</body>
</HTML>

-------------------------------------------------------------------
方法三(使用XmlHttp):
在任一页面的Page_Load()里面写:
if (Request.QueryString["GetData"] == "1")
{
Response.ClearContent();
string copyValue = null;
for (int i=0; i<s.Length; i++)
{
copyValue += s[i] + ",";
}
Response.Write(copyValue.Substring(0, copyValue.Length - 1));
Response.End();
}
然后在要得到值的js所在页面写:
function AsyncCopy()
{
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
xmlhttp.open("GET","ModifyToYourPageUrl.aspx?GetData=1", false);
xmlhttp.send();
var iniArr = xmlhttp.responseText;
eval("my_array = new Array(" + iniArr + ");");
//下面为测试用代码
for (i=0; i<my_array.length; i++)
{
document.all("num").innerText += my_array[i] + ", ";
}
}
用一个按钮的单击事件启动:
<input type="button" onclick="javascript:AsyncCopy();" value="Copy">

-------------------------------------------------------------------
方法四(使用Page.RegisterArrayDeclaration()):
在Page_Load()中写:
System.Text.StringBuilder sb = new System.Text.StringBuilder(512);
foreach (int i in s)
{
sb.Append(i);
sb.Append(',');
}
sb.Length--;
Page.RegisterArrayDeclaration("my_array", sb.ToString());
这样就在客户端生成了一个名为my_array的数组,可以直接用
备注:上面的代码仅供演示,一些数组大小用的都是常数,而且没有异常处理,使用时需要完善。

总结:
1、最简单、方便的是第四种方法。有了这种方法,第一种方法就是多余的了。
2、xmlhttp和webservice这两种方法不会影响页面的初次加载时间,可以在需要的时候随时获得数组,适合大数据量的传输。同时这两种方法不受页面的限制,在A页面的js可以获得B页面的数组或者另一个Webservice的计算结果。

第四种方法,MSDN里介绍为:

<%@ Page Language="C#"%>
<script runat="server">
   public void Page_Load(Object sender, EventArgs e)
   {
     // Define the array name and values.
     String arrName = "MyArray";
     String arrValue = "\"1\", \"2\", \"text\"";
    
     // Define the hidden field name and initial value.
     String hiddenName = "MyHiddenField";
     String hiddenValue = "3";
    
     // Define script name and type.
     String csname = "ConcatScript";
     Type cstype = this.GetType();
        
     // Get a ClientScriptManager reference from the Page class.
     ClientScriptManager cs = Page.ClientScript;
     // Register the array with the Page class.
     cs.RegisterArrayDeclaration(arrName, arrValue);
     // Register the hidden field with the Page class.
     cs.RegisterHiddenField(hiddenName, hiddenValue);
     // Check to see if the   script is already registered.
     if (!cs.IsClientScriptBlockRegistered(cstype, csname))
     {
       StringBuilder cstext = new StringBuilder();
       cstext.Append("<script type=text/javascript> function DoClick() {");
       cstext.Append("Form1.Message.value='Sum = ' + ");
       cstext.Append("(parseInt(" + arrName + "[0])+");
       cstext.Append("parseInt(" + arrName + "[1])+");
       cstext.Append("parseInt(" + Form1.Name + "." + hiddenName + ".value));} </");
       cstext.Append("script>");
       cs.RegisterClientScriptBlock(cstype, csname, cstext.ToString(), false);
     }
   }
</script>
<html>
   <head>
     <title>ClientScriptManager Example</title>
   </head>
   <body>
<form     id="Form1"
             runat="server">
      <input type="text"
             id="Message" />
      <input type="button"
             onclick="DoClick()"
             value="Run Script">
</form>
   </body>
</html>


[转]:http://hi.baidu.com/daijun2007/blog/item/28554a08f0bc32d262d9861e.html

另,当然也可用Ajaxpro来做啊

in cs file:
public partial class tempClass
{
protected void Page_Load(object sender, EventArgs e)
{

//注册AJAX
AjaxPro.Utility.RegisterTypeForAjax(typeof(tempClass));
}
[AjaxPro.AjaxMethod()]
public void CreateArray(int m,int n)
{
char[][] str = new char[m][];
for (int i = 0; i < n; ++ i)
{
str[n] = new char[500];
}

foreach(char ch in str)
{
hidField1.Vlaue=ch.ToString()+",";
}
}
}

----------in aspx file
<script language="javascript" type="text/javascript">
function getArr()
{
TempClass.CreateArray(10,10);
//获得hidField1的值,分割逗号,循环打出.时间关系到此为止,未测代码
}

 

posted on 2008-09-23 09:33  赛纳行星  阅读(632)  评论(0编辑  收藏  举报