我是靠谱客的博主 务实猎豹,这篇文章主要介绍原生JS进行AJAX请求与jQuery中的AJAX方法,现在分享给大家,希望可以做个参考。

ajax:

概念:

Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。
Ajax = 异步 JavaScript 和 XML 或者是 HTML(标准通用标记语言的子集)。
Ajax 是一种用于创建快速动态网页的技术。
Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。(百度百科)
实现:

  1. get方式:(如果有参数需要传递要用’?'拼接在地址后面)
复制代码
1
2
3
4
5
6
7
8
9
let xhr = new XMLHttpRequest(); xhr.open("GET","http://localhost:9000");//本地服务器端口9000 xhr.send(null); xhr.onreadystatechange = function(){ if(this.readyState===4&&this.status===200){ console.log(this.responseText); } }
  1. post方式:
复制代码
1
2
3
4
5
6
7
8
9
let xhr = new XMLHttpRequest(); xhr.open("POST","http://localhost:9000");//本地服务器端口9000 xhr.send(data); //发送参数数据 xhr.onreadystatechange = function(){ if(this.readyState===4&&this.status===200){ console.log(this.responseText); } }

jQuery中的ajax实现:

  1. get方式:

1)无参数传递

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getData() { // get 无参 $.ajax({ url:"http://localhost:3000", //服务器地址 type:"GET", //请求类型 success:function(msg){ //接收成功时的数据 console.log(msg); }, error:function(err){ console.log(err); } }); }

2)有参数传递

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getData() { //get 有参数 $.ajax({ url:"http://localhost:4000", type:"GET", data:"name=java", success:function(data){ console.log(data); }, error:function(err){ console.log(err); } }); }
  1. post方式

1)无参数传递:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getData() { //post 无参 $.ajax({ url:"http://localhost:3000", //服务器地址 type:"POST", //请求类型 success:function(msg){ //接收成功时的数据 console.log(msg); }, error:function(err){ console.log(err); } }); }
  1. 有参数传递:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function getData() { //post有参数 $.ajax({ url: "http://localhost:5000", type: "POST", // data: "username=admin&pwd=123", data:{username:"admin",pwd:"123"}, success: function (msg) { //接收成功时的数据 console.log(msg); }, error: function (err) { console.log(err); } }); }
  1. jsonp格式解决跨域:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getData() { $.ajax({ url:"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=美食", dataType:"jsonp", //支持jsonp jsonp: "cb",//服务端用于接收callback调用的function名的参数 success:function(data){ console.log("正确:",data); }, error:function(err){ console.log('错误:',err); } }); }

注意:调用后进error一般都是返回的数据格式问题

最后

以上就是务实猎豹最近收集整理的关于原生JS进行AJAX请求与jQuery中的AJAX方法的全部内容,更多相关原生JS进行AJAX请求与jQuery中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(103)

评论列表共有 0 条评论

立即
投稿
返回
顶部