You even add a backend page for every ajax request!
Are you even thinking, Nima, it would be great if you could directly call methods in C# class files? ! (FishLi has made a framework here, you can check it out if you are interested)
However, you may have forgotten that we are programmers, we are lazy, and we want the computer to do more things for us! (Pretend to be 13 here), but in fact, Microsoft and JQuery experts have already helped us solve this small problem.
The calls are roughly divided into the following categories:
1. Call without parameters and return value
Front-end JS code:
$("#btn1").click(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CalledByJquery.asmx/HelloWorld",
data : "{}",
dataType : "json",
success: function(json) { alert(json.d); },
error: function(error) {
error.response Text);
Backend WebMethod code:
Copy code
The code is as follows: [ WebMethod]public string HelloWorld(){
return "Hello World";
}
The result of debugging with Google:
2. Calling with simple parameters and simple return values
Front-end JS code:
Copy the code
url: "CalledByJquery.asmx/SimpleReturns",
data : "{name:'Zhang San'}",
dataType: "json",
success: function(json) { alert(json.d); },
error: function(error) {
alert("Calling error" error.responseText ;
Backend WebMethod code:
[WebMethod]
public string SimpleReturns(string name)
{
return String.Format("Your name is {0}", name);
}
Results of debugging with Google:
3. Calling with complex parameters and complex return values
Front-end JS code:
$("#btn3").click(function() {
$. ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CalledByJquery.asmx/Get StudentList",
data: "{stu ; function(error) {
;
Backend WebMethod:
Copy code
new Student{ID=1,Name="张Three"},
new Student{ID=2,Name="李四"}
since Add(stu);
return studentList;
}
The result of debugging with Google:
4. Calling WebMethod that returns anonymous objects
Front-end JS code:
Copy code
The code is as follows:
$("#btn4").click(function() {
charset=utf -8",
url: "CalledByJquery.asmx/ReturnNoNameClass",
data: "{}",
dataType: "json",
Success: function(json) { alert(json. d); },
error: function(error) {
alert("Calling error" error.responseText);
}
});
});
Backend WebMethod code:
[WebMethod]
public object ReturnNoNameClass()
return new {ID = 1, Name = "Zhang San" }; Result:
Haha, at this point, do you also feel that it is so easy? Mom no longer has to worry about my study. In fact, many things are very simple, but no one Tell us, but we ourselves do not have this need in actual development, so it has caused certain obstacles to our development.
Therefore, communication is so important!