jquery是一个优秀的js框架,自然对js原生的ajax进行了封装,
封装后的ajax的操作方法更简洁,功能更强大,与ajax操作
相关的jquery方法有如下几种:
Ajax 请求
- $.ajax([options])
- load(url, [data], [callback])
- $.get(url, [data], [fn], [type])
- $.getJSON(url, [data], [fn])
- $.getScript(url, [callback])
但开发中 经常使用的有三种:
1)$.get(url, [data], [callback], [type])
2)$.post(url, [data], [callback], [type])
url:代表请求的服务器端地址
data:代表请求服务器端的数据(可以是key=value形式也可以是json格式)
callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)
type:表示服务器端返回的数据类型(jquery会根据指定的类型自动类型转换)
常用的返回类型:text、json、html等
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="jquery-1.11.3.min.js"></script> <script type="text/javascript"> //get异步访问 function fun1() { $.get("/WEB22/ajaxServlet1", //请求的web端的资源地址 { "name" : "zhangsan", "age" : 20 }, //客户端向服务器端发送的数据 function(data) { //载入成功时的回调函数,其中data是服务器返回给客户端的数据 alert(data.name); }, "json" //[type] 返回内容的格式 ); } //post异步访问 function fun2() { $.post("/WEB22/ajaxServlet1", //请求的web端的资源地址 { "name" : "zhangsan", "age" : 20 }, //客户端向服务器端发送的数据 function(data) { //载入成功时的回调函数,其中data是服务器返回给客户端的数据 alert(data.name); }, "json" //[type] 返回内容的格式 ); } </script> </head> <body> <input type="button" value="get访问服务器端" onclick="fun1()"> <span id="span1"></span> <br> <input type="button" value="post访问服务器端" onclick="fun2()"> <span id="span2"></span> <br> </body> </html>
3)$.ajax( { option1:value1,option2:value2... } ); ---- 以后在掌握
常用的option有如下:
async:是否异步,默认是true代表异步
data:发送到服务器的参数,建议使用json格式
dataType:服务器端返回的数据类型,常用text和json
success:成功响应执行的函数,对应的类型是function类型
type:请求方式,POST/GET
url:请求服务器端地址
function fn3(){ $.ajax({ url:"/WEB22/ajaxServlet2", async:true, type:"POST", data:{"name":"lucy","age":18}, success:function(result){ alert(result); }, error:function(){ alert("请求失败"); }, dataType:"json" }); }