jQuery中的ajax、jquery中ajax全局事件、load实现页面无刷新局部加载、ajax跨域请求

jQuery中使用ajax:

在jQuery中使用ajax首先需要引入jQuery包,其引入方式可以采用网络资源,也可以下载包到项目文件中,这里推荐下载包到文件中;市面上有多个版本的jQuery库,这里到官网:https://jquery.com/download/随意找个比较老的版本即可,后面学完node可以使用npm更方便地下载到具体的版本,这里就不做过多强调了;下载完后要找到文件:jquery-1.12.4.zip\jquery-1.12.4\dist - 这个位置的文件就是要引入项目的文件,解压大小为 2.3 MB左右,其用法如下:

	//1.脚本之前引入jQuery文件:
    <script src="jquery.min.js"></script>
    //2.$ajax()是jQuery的ajax API,最基础的可以传两个参数,参数一为URL地址;参数二为对象;习惯传入一个对象作为参数,URL地址可以在这个对象中设置:
        $.ajax('time.php', {
     
            type: 'post', //提交方式,当为post时请求是通过请求体传递,当为get时,请求是通过URL传递
            success: function(result) {
      //请求成功后的回调函数,里面的参数是响应体
                console.log(result);
            };
        });
    
        $.ajax({
     
            url: 'time.php',
            type: 'get',
            data: {
     //data给服务端传递参数,后面跟一个对象。
                id: 1,
                name: 'kuhai',
                age: 18
            }, 
          	dataType: 'json', //当服务端没有设置Content-Type: application/json时,可以通过dataType:'json'设置响应体数据的类型。
            success: function(result) {
     
                console.log(result);/result会根据服务端设置的header('Content-Type: application/json')做出对应的响应,而原生的是不会根据服务端做出对应的响应,jQuery特有的。
            }
        });

jQuery中ajax的基本使用方法:

	<script>
        $.ajax({
      
            url: 'time.php',
            type: 'get',
            beforeSend: function(xhr) {
      
                // 在所有发送请求的操作(open, send)之前执行
                console.log('beforeSend');
            },
            success: function(res) {
      
                //只有请求成功(状态码为200)才会执行这个函数
                console.log('success')
            },
            error: function(err) {
      
                //只有请求不正常(状态码不为200)才会执行
                console.log('error')
            },
            complete: function(com) {
      
                // 不管是成功还是失败都会执行这个 complete 函数
                console.log('complete')
            }
        });
    script>

jQuery中ajax快捷操作:

	<script>
        // 以get的方式请求:
        $.get('time.php', {
      
            id: 1,
            name: 'ming'
        }, function(result) {
      
            console.log(result);
        });
    
        // 以post的方式请求:
        $.post('json.php', {
      
            age: 18
        }, function(res) {
      
            console.log(res);
        });
    
        // 以json数据格式的方式请求:Request Method默认值: GET
        $.getJSON('json.php', {
      
            gender: 1
        }, function(sex) {
      
            console.log(sex);
        });
    script>

jQuery中ajax全局事件:

jQuery中全局事件指:ajaxStart和ajaxStop事件,只要有ajax发生或结束就会执行此事件,常用于做加载进度条效果:(nprogress是一个做进度条的插件,有兴趣的话可以到官方文档学习)

	<script>
        $(document).ajaxStart(function() {
      
                // 只要有 ajax 请求发生就会执行此函数,函数中可以设计多种逻辑代码
            })
            .ajaxStop(function() {
      //注意这里为链式调用
                // 只要有 ajax 请求结束就会执行此函数,函数中可以设计多种逻辑代码
            })
        })
    script>

jQuery中不刷新页面实现局部加载:

jQuery中load(url,data,function(response,status,xhr))方法是使用ajax对数据加载,URL是数据接口地址,data是请求时向服务器发送的数据,function是请求完成时执行的函数(response请求的结果,status请求状态,XMLHttpRequest对象);此方法只传入页面的URL时,如果URL字符串中有空格且后面为一个页面元素的选择器,则只请求选择器这个元素,这样就可以实现页面局部刷新效果,如:

	
    
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <script src="jquery.min.js">script>
    head>
    <body>
        <div>
            <a class="list" href="index.html">页面1a>
            <a class="list" href="index2.html">页面2a>
            <a class="list" href="index3.html">页面3a>
        div>
        <main id="main">
            <h2>页面1h2>
        main>
        <script>
            $(function($) {
      
                // 点击时拿到被点击的a标签中的href属性值,通过load方法中ajax请求数据
                $('.list').on('click', function() {
      
                    var url = $(this).attr('href');
                    $('#main').load(url + ' #main');//url字符串中使用空号+选择器实现只加载选择器指定的元素:'index2.html #main'
                    return false;//阻止a标签默认跳转事件
                })
            })
        script>
    body>
    html>

下面是index.html中a标签地址指向页面的代码:

	
    <main id="main">
        <h2>页面2h2>
    main>
    
    
    <main id="main">
        <h2>页面3h2>
    main>

jQuery中JSONP:

	<script>
        $.ajax({
      
            url: 'http://day-03.io/test/server.php',
            dataType: 'jsonp',
            success: function(res) {
      
                console.log(res)
            }
        })
    script>

ajax跨域请求:

实际中ajax中已经支持跨域请求,只需要在服务端设置:header(‘Access-Control-Allow-Origin: *’)此配置,即可实现ajax跨域请求,如:

	<script>
        $.get('http://day-03.io/test/cors.php', {
      }, function(res) {
      
            console.log(res);
        });
    script>

服务端代码:

	
    $data = time();
    // 一行代码允许跨域请求
    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');
    echo json_encode($data);

提示:本文图片等素材来源于网络,若有侵权,请发邮件至邮箱:[email protected]联系笔者删除。
笔者:苦海

你可能感兴趣的:(Ajax,jQuery,javascript,jquery,ajax,前端)