jQuery 发送 AJAX 请求
AJAX 请求状态
xhr.readyState 可以用来查看请求当前的状态
参考官方文档的链接:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/readyState
0: 表示 XMLHttpRequest 实例已经生成,但是 open()方法还没有被调用
1: 表示 send()方法还没有被调用,仍然可以使用 setRequestHeader(),设定 HTTP请求的头信息。
2: 表示 send()方法已经执行,并且头信息和状态码已经收到。
3: 表示正在接收服务器传来的 body 部分的数据。
4: 表示服务器数据已经完全接收,或者本次接收已经失败了
jQuery 中的 AJAX
get 请求
$.get(url, [data], [callback], [type])
url:请求的 URL 地址。
data:请求携带的参数。
callback:载入成功时回调函数。
type:设置返回内容格式,xml, html, script, json, text, _default
post 请求
$.post(url, [data], [callback], [type])
url:请求的 URL 地址。
data:请求携带的参数。
callback:载入成功时回调函数。
type:设置返回内容格式,xml, html, script, json, text, _default。
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"><title>jQuery 发送 AJAX 请求</title><link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"><script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body><div class="container"><h2 class="page-header">jQuery发送AJAX请求 </h2><button class="btn btn-primary">GET</button><button class="btn btn-danger">POST</button><button class="btn btn-info">通用型方法ajax</button></div><script>$('button').eq(0).click(function(){$.get('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){console.log(data);},'json');});$('button').eq(1).click(function(){$.post('http://127.0.0.1:8000/jquery-server', {a:100, b:200}, function(data){console.log(data);});});$('button').eq(2).click(function(){$.ajax({//urlurl: 'http://127.0.0.1:8000/jquery-server',//参数data: {a:100, b:200},//请求类型type: 'GET',//响应体结果dataType: 'json',//成功的回调success: function(data){console.log(data);},//超时时间timeout: 2000,//失败的回调error: function(){console.log('出错啦!!');},//头信息headers: {c:300,d:400}});});</script> </body> </html>
总结
以上是生活随笔为你收集整理的jQuery 发送 AJAX 请求的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: axios 发送 AJAX请求
- 下一篇: jQuery 对象和 DOM 对象