一.Js
原生的ajax
1.js
原生的ajax
的开发步骤
1.1 创建ajax
引擎对象
1.2 为ajax
引擎对象绑定监听服务器变化的事件设置回调函数
回调函数:服务器再客户端进行响应之后,ajax
会自动调用这个函数
(自定义函数,服务器响应成功后,ajax
自动调用函数)
1.3 绑定提交地址
1.4 发送请求
1.5 接收响应数据
2.js
原生的ajax
代码实现
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生ajax</title>
</head>
<body>
<button id="btn" >原生的ajax发送请求</button>
<script>
let xhr=new XMLHttpRequest();//获取ajax引擎对象
// xhr.open(method,url,asyns) method:请求方式,url:匹配的controller,asyns:是否异步
xhr.open("GET","http://localhost:8080/text",true)//建立连接
xhr.send();//发送请求
xhr.onreadystatechange=function (){//获取响应(回调函数)
if(xhr.readyState==4 && xhr.status==200){//xhr.readyState请求是否完成(0,1,2,3,4) xhr.status:请求是否成功
console.log(xhr.responseText)//服务端响应的内容在responseText属性中
}
}
</script>
</body>
</html>
controller
package com.lzh.ajax.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class GoodsController {
@CrossOrigin("*")// @CrossOrigin(url) 从url发送过来的请求允许通过
@RequestMapping("/text")
@ResponseBody
public String test(){
return "hello";
}
}
二.jQuery
框架的ajax
1.GET
请求
语法:jQuery.get(url,[data],[callback],[type])
url
:请求服务器路径
data
:发送到服务器的数据,键值对的形式
callback
:回调函数,服务器响应成功,ajax
会自动执行这个回调函数
type
:预设服务器返回的数据类型(json
,text
)
导入jQuery
的框架
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用jQuery框架的ajax的get请求方式</title>
<script src="/static/js/jquery.js"></script>
</head>
<body>
<button id="b" onclick="on()">jQuery的get请求</button>
<script>
function on(){
$.get(
"http://localhost:8080/jget",
"username: lzh",
function(data){
alert(data)
},"text"
)
}
</script>
</body>
</html>
controller
@CrossOrigin("*")
@RequestMapping("/jget")
@ResponseBody
public String get(HttpServletRequest request){
String username = request.getParameter("username");
System.out.println(username);
return "jQuery的get";
}
2.POST
请求
语法:jQuery.post(url,[data],[callback],[type])
url
:请求服务器路径
data
:发送到服务器的数据,键值对的形式
callback
:回调函数,服务器响应成功,ajax
会自动执行这个回调函数
type
:预设服务器返回的数据类型(json
,text
)