使用JavaScript調用aspx后台代碼


方法1:js同步調用

觸發:

onclick="javascript:share('<%# Eval("id_File") %>')"

頁面函數:

 function share(id_File) {
            var a = '<%= ShareDoc("' + id_File + '") %>';
            alert(a);

        }

后台cs函數:

  public string ShareDoc(string id_File)
        {
            return "后台函數[" + id_File + "]";
        }

 

方法2:JQuery ajax異步調用

觸發:

onclick="javascript:download('<%# Eval("FileNewName") %>','<%# Eval("FileExtName") %>')"

前台函數:

   function download(p1, p2) {
           
            $.ajax({
                url: 'MyDocList.aspx/DownloadDoc',
                contentType: 'application/json; charset=utf-8',
                datatype: 'json',
                type: 'POST',
                data: '{FileNewName:"' + p1 + '",FileExtName:"' + p2 + '"}', //參數
                success: function(result) {//成功后執行的方法
                    alert(result.d); // 后台返回值
                },
                error: function(result) {//失敗執行的方法
                    alert("error:" + result.responseText);
                }
            });
         
        }

后台cs函數:

  [WebMethod]
        public static string DownloadDoc(string FileNewName, string FileExtName)
        {

            string filePath = Server.MapPath(string.Format("~/FileUpload/{0}.{1}", FileNewName, FileExtName));
            if (System.IO.File.Exists(filePath))
            {
                FileInfo file = new FileInfo(filePath);
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解決中文亂碼
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //解決中文文件名亂碼    
                Response.AddHeader("Content-length", file.Length.ToString());
                Response.ContentType = "appliction/octet-stream";
                Response.WriteFile(file.FullName);
                Response.End();
            }
            return filePath;
        }

注意:下載功能是錯誤的。但是函數可以這樣調用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM