持续学习&持续更新中…
学习态度:守破离
同步请求和异步请求
未学AJAX之前向服务器提交请求的方式
同步和异步
- 同步请求:不能局部更新,只能更新整个页面。
- 异步请求:可以局部更新页面。
AJAX
什么是AJAX
AJAX的常见使用方式
- https://jquery.cuishifeng.cn/jQuery.Ajax.html
- https://zh.javascript.info/xmlhttprequest
原生
- GET
function get() {
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest()
// 配置请求方法和URL(第三个参数如果是true代表异步,false代表同步,默认是true)
xhr.open('GET', 'http://localhost:8080/ajax/hello?message=hello_ajax_get')
// 配置服务器返回数据的格式
xhr.responseType = 'json'
// 发送请求
xhr.send()
// 监听响应
xhr.onload = function () {
if (xhr.status !== 200) return
console.log(xhr.response)
}
}
- POST
function post() {
const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:8080/ajax/hello')
xhr.responseType = 'json'
// 设置请求头(以表单形式提交)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
// 发送请求(如果是POST请求,需要传递请求体)
xhr.send('message=hello_ajax_post')
xhr.onload = function () {
if (xhr.status !== 200) return
console.log(xhr.response)
}
}
- POST-FILE
function postFile() {
const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:8080/ajax/hello')
xhr.responseType = 'json'
// 发送请求(表单-文件上传的形式)
const body = new FormData()
body.append('message', 'hello_ajax_post-file')
xhr.send(body)
xhr.onload = function () {
if (xhr.status !== 200) return
console.log(xhr.response)
}
}
jQuery
参考
李明杰: Java从0到架构师②JavaEE技术基石.
本文完,感谢您的关注支持!