ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

ajax笔记

2022-06-17 20:05:46  阅读:157  来源: 互联网

标签:function option url 笔记 xhr ajax data


Ajax笔记

目录:

课程知识点

1、异步

2、XMLHttpRequest

3、XML

4、Jason

5、兼容性

6、封装Ajax工具函数

7、jQuery中的ajax

8、案例练习

引入

1、浏览器与服务器间通过报文进行数据的验证与传输

请求报文;请求行、请求头、请求主体

响应报文:状态行、响应头、响应主体

image-20220508105646818

image-20220508105834707

1、异步

image-20220508124009376

ajax通过get发送数据

 document.querySelector('input').onblur=function(){
            document.querySelector('h3').innerHTML='验证中';
            var xhr=new XMLHttpRequest();//创建异步对象
            xhr.open('post','getData.php?name='+this.value);
            xhr.setRequestHeader('11','11');//设置请求头
            xhr.onload=function(){//回调函数
                console.log(xhr.responseText);
            }
            xhr.send(null);//请求主体发送,没有写null



        }
<?php
$name=$_GET['name'];
// 假数据模拟
$arr

?>

ajax通过post发送数据

image-20220508225848239

案例:聊天机器人

<script type="text/javascript" src='js/jquery.min-1.72.js'></script>

<!--  定义自己的 模板  -->
<script type="text/html" id='self'>
  <div class="self clearfix">
    <a href="#" class='f_r'>人</a>
    <p class='f_r'></p>
  </div>
</script>

<!--  定义机器人的模板   -->
<script type="text/html" id='robot'>
  <div class="robot clearfix">
    <a href="#" class='f_l'>机</a>
    <p class='f_l'></p>
  </div>
</script>

<!-- 自己的js代码 -->
<script type="text/javascript">
  $(function () {
    // 绑定点击事件
    $('.sendButton').click(function () {
      //1.创建异步对象
      var xhr = new XMLHttpRequest();
      //2.设置属性(请求头,请求行)
      xhr.open('get', 'chat.php');
      //3.发送请求
      xhr.send(null);
      // 创建 自己的 聊天框
      $($('#self').html()).children('p').html($('.inputBox').val()).end().appendTo('.message');

      //4.注册状态改变事件
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          //5.判断状态&请求是否成功并使用数据
          $($('#robot').html()).children('p').html(xhr.responseText).end().appendTo('.message');
        }
      }
    })
  })
</script>
<?php 
	
	// 休息一会
	sleep(1);

	// 获取 用户发送的 消息  (可选)
	// 后端 对于 用户发过来的 时候 是否 使用 (可选)
	
	// 根据 发送 过来的 消息 返回 不同的内容
	$messageList =array(
		'你好啊^_^',
		'我没有吃饭哦',
		'老地方见',
		'讨厌',
		'死鬼  嘿嘿嘿',
		'西兰花好好吃' 
	 );

	// 从 数组中 每次 随机 取出
	// array_rand 返回的 是一个 随机的 下标
	$randomKey = array_rand($messageList,1);

	// 使用 随机 下标 返回 随机的 值
	echo $messageList[$randomKey];


 ?>

同步

image-20220510124431054

Json(掌握)

json的载体是字符串

写法

image-20220510210237870

案例:lol

<script>
  // 需求1
  // 点击  getData
  // 获取 heroNum 的value
  $(function () {
    // 获取英雄列表
    $('.getData').click(function () {
      //1.创建异步对象
      var xhr = new XMLHttpRequest();
      //2.设置请求行
      xhr.open('get', './api/HeroInfo_List_get.php?num=' + $('.heroNum').val());
      //3.设置请求头(get请求可以省略)
      //4.注册状态改变事件
      xhr.onreadystatechange = function () {
        //4.1判断状态&请求是否成功并使用数据
        if (xhr.readyState == 4 && xhr.status == 200) {
          // 解析数据
          var dataObj = JSON.parse(xhr.responseText);
          // 循环生成对应的结构
          // dataObj.data 数据在data这个数组中
          for (var i = 0; i < dataObj.data.length; i++) {
            // 克隆结构
            var $cloneCol = $('.col-xs-4').first().clone();//使用first避免多次复制
            // 更改内容
            $cloneCol.find('img').attr('src', dataObj.data[i].champion_icon);
            $cloneCol.find('span').html(dataObj.data[i].champion_name);

            // 添加到页面上
            // appendTo 这个方法是jQuery 参数可以写 jQuery对象 也可以写 选择器
            $cloneCol.appendTo($('.row'));
            // $cloneCol.appendTo('.row');
          }
        }
      }
      //5.发送请求
      xhr.send(null);
    })

    // 为row中的 a标签绑定点击事件
    // 因为a标签是动态生成的 为了一劳永逸 直接绑定给 row 指定由 a触发
    $('.row').on('click', 'a', function () {
      // console.log('你点我了哦');
      //1.创建异步对象
      var xhr = new XMLHttpRequest();
      //2.设置请求行
      xhr.open('post', './api/HeroInfo_details_post.php');
      //3.设置请求头(get请求可以省略)
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      //4.注册状态改变事件
      xhr.onreadystatechange = function () {
        //4.1判断状态&请求是否成功并使用数据
        if(xhr.readyState==4&&xhr.status==200){//如果请求成功 
          // console.log(xhr.responseText);
          // 解析数据,回来的是zi'fu'chuanjson数据
          var dataObj = JSON.parse(xhr.responseText);
          console.log(dataObj);

          // 修改内容
          // 外号
          $('.jumbotron').find('span').first().html(dataObj.data.champion_title);
          // 名字
          $('.jumbotron').find('span').last().html(dataObj.data.champion_name);
          // 图片,涉及标签属性的要使用attr
          $('.jumbotron').find('img').attr('src',dataObj.data.champion_icon);
          // 位置
          $('.jumbotron').find('p').first().html(dataObj.data.champion_tags);
          // 个性签名
          $('.jumbotron').find('p').last().html(dataObj.data.champion_info);
          // a标签的href
          $('.jumbotron').find('a').attr('href',dataObj.data.champion_url);
          // $('.jumbotron').find('a').attr('herf',dataObj.data.champion_url)
          
          

          // 弹出模态框
          $('.modal').modal('show');
          // $('.modal').modal('show');
        }

      }
      //5.发送请求
      //$(),将返回的Dom转为jq对象
      xhr.send('name='+$(this).find('span').html());
      // xhr.send('name'+$(this).find('span').html());
    })
  })
</script>

ajax工具函数的封装

抽取相同点封装成js

代码执行流程

image-20220513170116422

/**
 * ajax工具函数get
 * @param {*} url 
 * @param {*} data (key1=value1,key2=value2)
 * @param {*} success 
 */
function get(url,data,success){
    var xhr=new XMLHttpRequest();
    if(data){
        url+='?';
        url+=data;
    }
    xhr.open('get',url);
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4&&xhr.status==200){
            success(xhr.responseText);

        }
    }
    xhr.send(null);
}
/**
 * ajax工具函数post
 * @param {*} url 
 * @param {*} data (key1=value1,key2=value2)
 * @param {*} success 
 */
function post(url,data,success){
    var xhr=new XMLHttpRequest();
    xhr.open('post',url);
    if(data){
        xhr.setRequestHeader('Content-type','application/x-www-from-urlencoded');
    }
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4&&xhr.status==200){
            success(xhr.responseText);

        }
    }
    xhr.send(data);
}

进一步优化封装

/**
 * 
 * @param {*} option 对象
 * (key1=value1,key2=value2)
 */
 function ajax_xhr(option){
    var xhr=new XMLHttpRequest();
    if(option.type=='get'&& option.data){
        option.url+='?';
        option.url+=option.data;
        option.data=null;//最后一步直接send

    };
    xhr.open(option.type,option.url);
    if(option.type=='post'&& option.data){
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    };
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4 && xhr.status==200){
            // option.success(xhr.responseText);//回调函数的参数
            // console.log(xhr.getResponseHeader('Content-type'));
            var type=xhr.getResponseHeader('Content-type');
            //是否为json
            if(type.indexOf('json')!=-1){
                option.success(JSON.parse(xhr.responseText));
            }//是否为xml
            else if(type.indexOf('xml')!=-1){
                option.success(xhr.responseXML);
            }
            else{
                option.success(xhr.responseText);
            }

        }
    };
    xhr.send(option.data);
}

工具函数的注册

$(function () {
        // 需求1
        $('.inputName').blur(function () {
            $('.cover').show();
            // 发送请求
            ajax({
                type: 'get',
                url: '_api/01.check.php',
                data: 'name=' + $('.inputName').val(),
                success: function (data) {
                    console.log(data);
                    $('.cover').hide();
                    // delay 让后面的动画 延迟一会调用
                    //fadein淡入,fadeout
                    $('.tips').html(data.message).fadeIn(1000).delay(2000).fadeOut();
                    // 如果可以注册 删除类名即可
                    if (data.status == 'can') {
                        $('.sub').removeClass('disabled');//去除注册禁用
                    }
                }
            })
        })

        // 需求3
        $('.sub').click(function(){
            if($(this).hasClass('disabled')==true){
                alert('洗洗睡啦');
                return;
            }
            $('.cover').show();//显示遮罩层
            ajax({
                url:'_api/register.php',
                type:'post',
                data:'name='+$('.inputName').val(),
                success:function(data){
                    $('.cover').hide();
                    $('.tips').html(data).fadeIn(1000).delay(1000).fadeOut(1000);
                    // 添加禁用的类名即可
                    $('.sub').addClass('disabled');
                }
            })
        })
    })

jquery里的ajax

调用方式:$.ajax({})与封装的差别不大

模板引擎

步骤:定义模板--》挖坑 、起名--》填坑(对象与模板结合)

案例:落网

步骤

​ 0.导入模板引擎

​ 1.定义模板

​ 2.挖坑 起名字

​ 挖坑 一般是取决于 数据

​ 3.填坑

​ 数据 服务器 ajax

​ 回调函数

​ 4.使用

<script type="text/javascript" src="./js/jquery-1.12.4.min.js"></script>
<!--
		步骤
			0.导入模板引擎
			1.定义模板
			2.挖坑 起名字
				挖坑 一般是取决于 数据
			3.填坑
				数据 服务器 ajax
				回调函数
			4.使用
	-->
<!--  导入模板引擎  -->
<script src='./js/template-web.js'></script>
<!-- 定义模板  -->
<script type='text/html' id='template'>
	
	<div class="item">//这部分是直接复制了原来的结构
				<a href="#" class="cover"><img src="{{path}}" alt=""></a>
				<div class="bottom">
					<a href="#">{{name}}</a>
					<div class="rightBox">
						<span class="icon-heart">{{star}}</span>
						<span class="icon-comment">{{message}}</span>
					</div>
			</div>
	</div>
</script>

<script>
	// 获取数据
	$(function(){
		$('#getMore').click(function(){
			$.ajax({
				url:'_api/luowang.php',
				data:{
					index:3
				},
				success:function(data){
					console.log(data);
					// 填坑
				 var result =	template('template',data.item);//将填好的东西包括结构
					console.log(result);
					$('.container').append(result);
				}
			})
		})

		// 获取多条
		$('#getSome').click(function(){
			$.ajax({
				url:'_api/luowang_getSome.php',
				data:{
					num:Math.floor((16*Math.random()))
					//向服务器提交要多少条数据
				},
				success:function(data){
						console.log(data);
						// 循环 填坑
						for(var i =0;i<data.items.length;i++){
							// 填坑 使用
							// 第一个参数是id,第二个是数据
							$('.container').append(template('template',data.items[i]));
						}
				}
			})
		})
	})
</script>

jsonp接口调用

相对于之前的ajax请求更改的地方为datatype:‘jsonp’

<script  src="./jquery-1.12.4.min.js"></script>
<script>
  $(function(){
    // 按钮1绑定点击事件
    $('input').first().click(function(){
      $.ajax({
        url:'https://api.asilu.com/query/image/baidu/',//接口地址,由其他提供
        success:function(data){
          console.log(data)
        },
        dataType:'jsonp'//不一样的地方
      })
    })
      // 按钮2绑定点击事件
    $('input').eq(1).click(function(){
      $.ajax({
        url:'https://api.asilu.com/phone/',//接口地址
        data:{
          phone:'15180120422'
        },
        success:function(data){
          console.log(data)
        },
          
        dataType:'jsonp'
      })
    })
  })
</script>

后台未对数据进行格式转换时用datapyte指定格式,数据可以转换成指定的格式

image-20220517000255488

跨域

不同源的网站间互相发送请求

有两种方法实现跨域

1、cros(h5才支持)

后台设置允许访问

image-20220517200927796

2、jsonp

jsonp利用了src属性支持跨域获取资源

image-20220517201258537

PHP文件返回的是js代码

src中jsonp原理

image-20220517202654411

image-20220517202820940

区别:

image-20220517203621848

标签:function,option,url,笔记,xhr,ajax,data
来源: https://www.cnblogs.com/asmithnal/p/16386917.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有