首页 > 代码库 > JS调用服务器端方法

JS调用服务器端方法

javascript函数中执行C#代码中的函数:
方法一:1、首先建立一个按钮,在后台将调用或处理的内容写入button_click中;
        2、在前台写一个js函数,内容为document.getElementById("btn1").click();
        3、在前台或后台调用js函数,激发click事件,等于访问后台c#函数;

方法二:1、函数声明为public             
           后台代码(把public改成protected也可以)
           public string ss()
           {
              return("a");
           }
        2、在html里用<%=fucntion()%>可以调用
           前台脚本
           <script language=javascript>
           var a = "<%=ss()%>";
           alert(a);
           </script>
方法三:1、<script language="javascript">
           <!- -
           function __doPostBack(eventTarget, eventArgument)
           {
              var theForm = document.Form1;     //指runat=server的form
              theForm.__EVENTTARGET.value = eventTarget;
              theFrom.__EVENTARGUMENT.value = eventArgument;
              theForm.submit();
           }
           -->
           </script>
           <input id="Button1" type="button" name="Button1" value="http://www.mamicode.com/按钮" onclick="javascript:__doPostBack(‘Button1‘,‘‘)">
        
方法四:<script language="javascript">
function SubmitKeyClick()
{
    if (event.keyCode == 13)
    {
        event.cancelBubble = true;
        event.returnValue = false;
        document.all.FunName.value="http://www.mamicode.com/你要调用的函数名";
        document.form[0].submit();
    }
}
</script>

<INPUT onkeypress="SubmitKeyClick()" id="aaa" type="text">
<input type="hidden" name="FunName"> 〈!--用来存储你要调用的函数 --〉

在.CS里有:
public Page_OnLoad()
{
if (!Page.IsPost())
{
string strFunName=Request.Form["FunName"]!=null?Request.Form["FunName"]:"";
//根据传回来的值决定调用哪个函数
switch(strFunName)
{
case "enter()":
enter() ; //调用该函数
break;
case "其他":
//调用其他函数
break;
default:
//调用默认函数
break;
}
}
}

public void enter()
{
//……比如计算某值
}

 

方法五 直接用XHtmlRequest, client callback, javascript访问Web Service或WebMethod.

以访问WebMethod为例:
1、ScriptManager的EnablePageMethod必须为true.  

HTML code
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
  <Scripts>
  <asp:ScriptReference Path="~/Scripts/MyScript.js" />
  </Scripts>   
</asp:ScriptManager>




2、服务器方法必须是static方法  

C# code
[System.Web.Services.WebMethod]
public static string[] GetStringArray(string s, int cnt)
{
  string[] stringArray = new string[cnt];
  Random rnd = new Random();
  for (int i = 0; i < cnt; i++)
  {
  stringArray[i] = string.Format("Random{0}: {1}-{2}",i, s, rnd.Next(cnt));
  }
  //throw new Exception("亲爱的错误");
  System.Threading.Thread.Sleep(3000);
  return stringArray;
}




3、可以把script代码放到.js文件里,如Scripts目录下的MyScript.js内。  

JScript code
function CallWebMethod(prefix,count)
{
  $get(‘result‘).innerText = "请稍侯...";
  PageMethods.GetStringArray(prefix, count, OnSuccess, OnFailed);
  return false;
}
function OnSuccess(stringArray)
{
  var s = "";
  for(var i = 0; i < stringArray.length; i++)
  {
  s += stringArray[i] + "\n";
  }
    
  $get(‘result‘).innerText = s;
}
function OnFailed(error, userContext, methodName)
{
  if(error != null)
  {
  alert("发生了亲爱的错误:" + error.get_message());
  }
}




//.aspx  

HTML code
<form id="form1" runat="server">
  <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
  <Scripts>
  <asp:ScriptReference Path="~/Scripts/MyScript.js" />
  </Scripts>   
  </asp:ScriptManager>
  <div>
  <asp:Label ID="LabelPrefix" AssociatedControlID="TextBoxPrefix" runat="server" Text="string prefix: "></asp:Label>
  <asp:TextBox ID="TextBoxPrefix" runat="server"></asp:TextBox>
  <asp:Label ID="LabelCnt" AssociatedControlID="TextBoxCnt" runat="server" Text="count: "></asp:Label>
  <asp:TextBox ID="TextBoxCnt" runat="server"></asp:TextBox>
  <cc1:FilteredTextBoxExtender
  ID="FilteredTextBoxExtenderCnt" runat="server"
  TargetControlID="TextBoxCnt"
  ValidChars="1234567890"
  >
  </cc1:FilteredTextBoxExtender>
  <input id="Button1" type="button" value="http://www.mamicode.com/button" TextBoxPrefix.ClientID %>‘).value,$get(‘<%= TextBoxCnt.ClientID %>‘).value)" />
  </div>
  <div id="result" style="border:solid 1px Maroon; margin: 10px; padding;5px;">
  </div>
</form>

 

转自:http://saint.blog.51cto.com/403308/410000

JS调用服务器端方法