日期:2014-05-18  浏览次数:20471 次

[求助]如何在javascript中调用服务器端的方法??
如我想当用户关闭网页时,就调用javascript中的logout方法,而logout方法中又调用了后台的test方法,请问要怎么写?

代码如下:

<%@   Page   Language= "C# "   AutoEventWireup= "true "   CodeFile= "Default2.aspx.cs "   Inherits= "Default2 "   %>

<!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   runat= "server ">
        <title> 无标题页 </title>
    <script   type= "text/javascript "   language   = "javascript ">
    function   logout()
    {
          Default2.test();
    }
    </script>
     
</head>
<body   onunload= "logout(); "   >
        <form   id= "form1 "   runat= "server ">
        <div>
       
        </div>
        </form>
</body>
</html>

_______________________________cs代码如下_________________________

using   System;
using   System.Data;
using   System.Configuration;
using   System.Collections;
using   System.Web;
using   System.Web.Security;
using   System.Web.UI;
using   System.Web.UI.WebControls;
using   System.Web.UI.WebControls.WebParts;
using   System.Web.UI.HtmlControls;

public   partial   class   Default2   :   System.Web.UI.Page
{
              protected   void   Page_Load(object   sender,   EventArgs   e)
        {
                AjaxPro.Utility.RegisterTypeForAjax(typeof(Default2));   //必要的
       
        }

     

        public   void   test()
        {
                Response.Write( " <script> alert( 'sdf! '); </script> ");
        }
}



------解决方案--------------------
试一下,在前台添加 <body onunload= "logout(); "...
添加一个LinkButton控件,将Text属性设为空,ID设为“doSth”,双击LinkButton,在后台LinkButton的Click事件中调用test()方法

前台脚本添加一句
function logout()
{
......
__doPostBack( 'doSth ', ' ');
}
------解决方案--------------------
原来你用的是Ajax...

添加Ajax.dll或者AjaxPro.dll的引用了么?

test()方法上面加这个

[Ajax.AjaxMethod()]
public void test()
{
Response.Write( " <script> alert( 'sdf! '); </script> ");
}