一、前端請求后台方式


一、前端請求后台方式

方法一:直接使用<%=%>調用

前台JS:

<script type = "text/javascript" >
    var methodStr = "<%=BehindMethod() %>";
   alert(methodStr); 
</script>

后台方法:

public static string BehindMethod()
{
    return "這是一個后台的方法";
}

方法二:用ajax調用

 前台JS:

<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript"> 
var params = '{ext:"p9hp"}';  //參數,注意參數名要注意和后台方法參數名要一致        
        $(function(){
           $("#btnOk").click(function(){
            $.ajax({
                type:"POST",  //請求方式
                url:"AjaxDemo.aspx/GetImg",  //請求路徑:頁面/方法名字
                data: params,     //參數
                dataType:"text",  
                contentType:"application/json; charset=utf-8",
                beforeSend:function(XMLHttpRequest){  
                    $("#tips").text("開始調用后頭方法獲取圖片路徑,請等待");
                    $("#imgFood").attr("src","image/loading.gif");
                },
                success:function(msg){  //成功
                    $("#imgFood").attr("src",eval("("+msg+")").d);  
                    $("#tips").text("調用方法結束");
                },
                error:function(obj, msg, e){   //異常
                    alert("OH,NO");
                }               
            });
        });
        });
</script>

頁面html:

<body>
    <form id="form1" runat="server">
    <div>
    <label id="tips"></label>
       <img id="imgFood" />
       <input value="點擊我,給你看一張圖片" type="button" width="35px" id="btnOk"  />

    </div>
    </form>
</body>

后台方法:

[System.Web.Services.WebMethod]
public static string GetImg(string ext)
{
    System.Threading.Thread.Sleep(5000);//為了有點等待的效果,延遲5秒
    StringComparer sc = StringComparer.OrdinalIgnoreCase;
    string[] extArr = new string[] { "php", "asp", "aspx", "txt", "bmp" };
    bool f = extArr.Any(s=>sc.Equals(s,ext));   //判斷傳入的后綴名是否存在

    if (f)
    {
        return "image/54222860.jpg";
    }
    return "image/star1.jpg";
}

方法三:AjaxPro (也是ajax)

第一步:下載AjaxPro.dll(或者AjaxPro.2.dll),並且添加引用到項目

第二步:修改配置文件web.config 

<system.web>
<httpHandlers>
      <!--注冊ajaxPro.2-->
      <add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
    </httpHandlers>
</system.web>

第三步:對AjaxPro在頁Page_Load事件中進行運行時注冊。如:

protected void Page_Load(object sender, EventArgs e)
{
    AjaxPro.Utility.RegisterTypeForAjax(typeof(AjaxDemo));  //注冊
}

第四步:創建服務器方法,並且用[AjaxPro.AjaxMethod]標注

[AjaxPro.AjaxMethod]
public string GetImgByAjaxPro()
{
    return "image/54222860.jpg";
}

第五步:前台JS的調用:

function GetMethodByAjaxPro() {
    var a = JustTest.AjaxDemo.GetImgByAjaxPro();//JustTest是當前的名字空間,AjaxDemo表示后台類
    document.getElementById("imgAjaxPro").src = a.value;
}

 


免責聲明!

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



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