你甚至为每个ajax请求添加一个后端页面!
你是不是甚至在想,尼玛,要是能够直接调用C#类文件中的方法就爽了?!(这里FishLi做了一个框架,有兴趣可以去看看)
可是,你大概忘记了,我们是程序员,我们是懒惰的,我们要让电脑给我们干更多的事情!(这里装装13),但其实,微软和JQuery大牛们早帮我们解决了这个小问题。
大致的调用分为以下几种:
一、无参数 有返回值的调用
前端JS代码:
$(\"#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) {
alert(\"调用出错\" + error.responseText);
}
});
});
后端WebMethod代码:
[WebMethod]
public string HelloWorld()
{
return \"Hello World\";
}
用谷歌调试的结果:
二、简单参数 简单返回值的调用
前端JS代码:
$(\"#btn2\").click(function() {
$.ajax({
type: \"POST\",
contentType: \"application/json; charset=utf-8\",
url: \"CalledByJquery.asmx/SimpleReturns\",
data: \"{name:\'张三\'}\",
dataType: \"json\",
success: function(json) { alert(json.d); },
error: function(error) {
alert(\"调用出错\" + error.responseText);
}
});
});
后端WebMethod代码:
[WebMethod]
public string SimpleReturns(string name)
{
return String.Format(\"您的姓名是{0}\", name);
}
用谷歌调试的结果:
三、 复杂参数 复杂返回值的调用
前端JS代码:
$(\"#btn3\").click(function() {
$.ajax({
type: \"POST\",
contentType: \"application/json; charset=utf-8\",
url: \"CalledByJquery.asmx/GetStudentList\",
data: \"{stu:{ID:\'6\',Name:\'ff\'}}\",
dataType: \"json\",
success: function(json) { alert(json.d); },
error: function(error) {
alert(\"调用出错\" + error.responseText);
}
});
});
后端WebMethod:
[WebMethod]
public List<Student> GetStudentList(Student stu)
{
List<Student> studentList = new List<Student>
{
new Student{ID=1,Name=\"张三\"},
new Student{ID=2,Name=\"李四\"}
};
//把从客户端传来的实体放回到返回值中
studentList.Add(stu);
return studentList;
}
用谷歌调试的结果:
四、返回匿名对象的WebMethod的调用
前端JS代码:
$(\"#btn4\").click(function() {
$.ajax({
type: \"POST\",
contentType: \"application/json; charset=utf-8\",
url: \"CalledByJquery.asmx/ReturnNoNameClass\",
data: \"{}\",
dataType: \"json\",
success: function(json) { alert(json.d); },
error: function(error) {
alert(\"调用出错\" + error.responseText);
}
});
});
后端WebMethod代码:
[WebMethod]
public object ReturnNoNameClass()
{
return new { ID = 1, Name = \"张三\" };
}
用谷歌调试的结果:
哈哈,到这里,你是不是也觉得so easy,妈妈再也不用担心我的学习了,其实很多东西都很简单,但没人告诉我们,而我们自己在实际开发中又没有这种需求,所以给我们的开发造成了一定的障碍,
所以,交流啊,是多么滴重要!