Ajax学习

发起跨域的Ajax请求:

域名的概念:

例如:www.baidu.comwww.jd.com

它们的主域名相同,二级域名不同,存在跨域。

跨域问题

一个页面发起的ajax请求,只能是与当前页域名相同的路径,出现的原因是浏览器的同源策略不允许非同源网站进行数据资源交互。浏览器可发起跨域请求但回收数据被同源策略拦截

常见的跨域:

在之前的学习中,有些HTML标签已经实现了跨域的访问功能。例如:

  1. img标签可以引入其他网站的图片
  2. link标签可以引入css文件
  3. scrip标签可以引入JavaScript文件
  4. iframe标签可以引入HTML页面

JSONP实现跨域访问:

JSONP全称为:“JSON with Padding” 是 JSON 的一种使用模式。

jsonp利用script标签的src不受同源策略限制。

script标签实现跨域防问:

定义script标签 ,src内指向服务器的地址和回调函数。

 <script>
    function af(data){
      console.log('nadi');
      console.log(data);
    }
    function abc(data) {
      console.log('拿到了Data数据:')
      console.log(data)
    }
  </script>
<!-- 保证调用一致使用查询字符串来调用 -->
  <script src="./js/getdata.js?callback=abc"></script>

实现简单的jsonp数据请求:

定义script标签内src指向接口地址后加jsonp和回调函数

<script>
    function abc(data) {
      console.log('JSONP响应回来的数据是:')
      console.log(data)
    }
  </script>

  <script src="http://ajax.frontend.itheima.net:3006/api/jsonp?callback=abc&name=ls&age=30"></script>

使用jQuery发起jsonp数据请求:

<script>
    $(function () {
      // 发起JSONP的请求
      $.ajax({
        url: 'http://ajax.frontend.itheima.net:3006/api/jsonp?name=zs&age=20',
        // 代表我们要发起JSONP的数据请求必须指定dataType为jsonp
        // 发起jsonp会随机调用回调函数
        // 想要自定义函数与函数名需要定义jsonp属性和jsonpcallback属性
        dataType: 'jsonp',
        jsonp: 'callback',//一般不用
        jsonpCallback: 'abc',
        success: function (res) {
          console.log(res)
        }
      })
    })
  </script>

案例:

淘宝搜素案例:

页面效果:

原理: 当输入搜索框时会弹出建议列表:需要利用到将数据传输到服务器端,回收建议数据后显示在页面中。

回收的数据进过模板引擎的渲染后加载到页面中

HTML页面:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
  <!-- 导入页面的基本样式 -->
  <link rel="stylesheet" href="./css/search.css" />
  <!-- 导入 jQuery -->
  <script src="./lib/jquery.js"></script>
  <!-- 导入模板引擎 -->
  <script src="./lib/template-web.js"></script>
</head>

<body>
  <div class="container">
    <!-- Logo -->
    <img src="./images/taobao_logo.png" alt="" class="logo" />

    <div class="box">
      <!-- tab 栏 -->
      <div class="tabs">
        <div class="tab-active">宝贝</div>
        <div>店铺</div>
      </div>
      <!-- 搜索区域(搜索框和搜索按钮) -->
      <div class="search-box">
        <input id="ipt" type="text" class="ipt" placeholder="请输入要搜索的内容" /><button class="btnSearch">
          搜索
        </button>
      </div>
      <!-- 搜索建议列表 -->
      <div id="suggest-list"></div>
    </div>
  </div>

  <!-- 模板结构 -->
  <script type="text/html" id="tpl-suggestList">
    {{each result}}
      <!--搜索建议项-->
      <div class="suggest-item">{{$value[0]}}</div>
    {{/each}}
  </script>

  <script>
    $(function () {
      // 1. 定义延时器的Id
      var timer = null
      // 定义全局缓存对象
      var cacheObj = {}

      // 2. 定义防抖的函数
      function debounceSearch(kw) {
        timer = setTimeout(function () {
          getSuggestList(kw)
        }, 500)
      }

      // 为输入框绑定 keyup 事件
      $('#ipt').on('keyup', function () {
        // 3. 清空 timer
        clearTimeout(timer)
        var keywords = $(this).val().trim()
        if (keywords.length <= 0) {
          return $('#suggest-list').empty().hide()
        }

        // 先判断缓存中是否有数据
        if (cacheObj[keywords]) {
          return renderSuggestList(cacheObj[keywords])
        }

        // TODO:获取搜索建议列表
        // console.log(keywords)
        // getSuggestList(keywords)
        debounceSearch(keywords)
      })

      function getSuggestList(kw) {
        $.ajax({
          url: 'https://suggest.taobao.com/sug?q=' + kw,
          dataType: 'jsonp',
          success: function (res) {
            // console.log(res)
            renderSuggestList(res)
          }
        })
      }

      // 渲染UI结构
      function renderSuggestList(res) {
        if (res.result.length <= 0) {
          return $('#suggest-list').empty().hide()
        }
        var htmlStr = template('tpl-suggestList', res)
        $('#suggest-list').html(htmlStr).show()

        // 1. 获取到用户输入的内容,当做键
        var k = $('#ipt').val().trim()
        // 2. 需要将数据作为值,进行缓存
        cacheObj[k] = res
      }
    })
  </script>
</body>

</html>

css文件:

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
}

.logo {
  width: 225px;
  height: 65px;
  margin: 50px 0;
}

.tabs {
  display: flex;
}
.tabs > div {
  width: 55px;
  height: 23px;
  line-height: 23px;
  text-align: center;
  cursor: pointer;
}

.tabs > div:hover {
  text-decoration: underline;
  color: #ff5700;
}

.tab-active {
  background-color: #ff5700;
  font-weight: bold;
  color: white;
}

.tabs > .tab-active:hover {
  color: white;
  text-decoration: none;
}

.search-box {
  display: flex;
  align-items: center;
}

.search-box .ipt {
  box-sizing: border-box;
  width: 500px;
  height: 34px;
  line-height: 30px;
  margin: 0;
  padding: 0;
  padding-left: 5px;
  outline: none;
  border: 2px solid #ff5700;
}

.btnSearch {
  margin: 0;
  height: 34px;
  border: none;
  background-color: #ff5700;
  color: white;
  letter-spacing: 1em;
  text-align: center;
  width: 90px;
  padding-bottom: 5px;
  outline: none;
  cursor: pointer;
}

.btnSearch:hover {
  opacity: 0.9;
}

#suggest-list {
  border: 1px solid #ccc;
  display: none;
}

.suggest-item {
  line-height: 30px;
  padding-left: 5px;
}

.suggest-item:hover {
  cursor: pointer;
  background-color: #eee;
}

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端VC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值