JavaScript calls three method instances in the background
- 2020-03-26 21:30:02
- OfStack
Method 1: direct use < % = % > call
JS: at the front desk
<script type="text/javascript">
var methodStr = "<%=BehindMethod() %>";
alert(methodStr);
</script>
After method:
public static string BehindMethod()
{
return " This is a background method ";
}
Method 2: call with ajax
Js: at the front desk
<script type="text/javascript" src="js/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
var params = '{ext:"p9hp"}'; //Parameter, notice that the parameter name is the same as the background method parameter name & PI;
$(function(){
$("#btnOk").click(function(){
$.ajax({
type:"POST", //Request way
url:"AjaxDemo.aspx/GetImg", //Request path: page/method name
data: params, // parameter
dataType:"text",
contentType:"application/json; charset=utf-8",
beforeSend:function(XMLHttpRequest){
$("#tips").text(" Start calling the back method to get the image path , Please wait for ");
$("#imgFood").attr("src","image/loading.gif");
},
success:function(msg){ // successful
$("#imgFood").attr("src",eval("("+msg+")").d);
$("#tips").text(" End of call method ");
},
error:function(obj, msg, e){ // abnormal
alert("OH,NO");
}
});
});
});
</script>
The HTML page:
<body>
<form id="form1" runat="server">
<div>
<label id="tips"></label>
<img id="imgFood" />
<input value=" Click on me to show you a picture " type="button" width="35px" id="btnOk" />
</div>
</form>
</body>
Background method:
[System.Web.Services.WebMethod]
public static string GetImg(string ext)
{
System.Threading.Thread.Sleep(5000);//Delay by 5 seconds to get some effect
StringComparer sc = StringComparer.OrdinalIgnoreCase;
string[] extArr = new string[] { "php", "asp", "aspx", "txt", "bmp" };
bool f = extArr.Any(s=>sc.Equals(s,ext)); //Determines whether the passed suffix name exists
if (f)
{
return "image/54222860.jpg";
}
return "image/star1.jpg";
}
Method 3: AjaxPro (also ajax)
Step 1: download the AjaxPro. DLL (or AjaxPro.2. DLL) and add a reference to the project
Step 2: modify the configuration file web. Config
<system.web>
<httpHandlers>
<!-- registered ajaxPro.2-->
<add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</httpHandlers>
</system.web>
Step 3: run time registration of AjaxPro in the page Page_Load event. Such as:
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(AjaxDemo)); // registered
}
Step 4: create the server method and annotate it with [AjaxPro.AjaxMethod]
[AjaxPro.AjaxMethod]
public string GetImgByAjaxPro()
{
return "image/54222860.jpg";
}
Step 5: foreground JS call:
function GetMethodByAjaxPro() {
var a = JustTest.AjaxDemo.GetImgByAjaxPro();//JustTest is the current namespace, and AjaxDemo is the background class
document.getElementById("imgAjaxPro").src = a.value;
}