jQuery粗略源码解析9 Ajax请求

2020-02-29  本文已影响0人  波拉拉

1 基础方法

1.1 $.ajax(options)方法

options常用参数解释:

$.ajax({
        url:"data.php",
        type:"get",
        cache:false,
        success:function (data) {
            console.log(data);//模拟数据
        }
    }).done(function (data) {
        console.log("请求成功"+data)
    });
$.ajax({
    url:"data/Official-website.json",
    type:"get",
    cache:false,
    dataType:"json"
}).done(
    function (data) {
        data1 = data.websites;
        var html = "";
        $.each(data1, function (i, item) {
            html += " <li><a href='" + item.site + "'>" + item.name + "</a></li>"
        });
        $("p:contains('企业官网')").next("ul").append(html);

        data2 = data.works;
        html = "";
        $.each(data2, function (i, item) {
            html += " <li><a href='" + item.site + "'>" + item.name + "</a></li>"
        });
        $("p:contains('工作相关')").next("ul").append(html);

        data3 = data.source;
        html = "";
        $.each(data3, function (i, item) {
            html += " <li><a href='" + item.site + "'>" + item.name + "</a></li>"
        });
        $("p:contains('图片素材')").next("ul").append(html);

        data4 = data.other;
        html = "";
        $.each(data4, function (i, item) {
            html += " <li><a href='" + item.site + "'>" + item.name + "</a></li>"
        });
        $("p:contains('其他大站')").next("ul").append(html);
    }
);

2 便捷方法

2.1 load(url, [data], [callback])

载入远程 HTML 文件代码并插入至 DOM 中。

//.load请求页头页尾
$(".header").load("data/header.html");
$(".footer").load("data/footer.html");
2.2 $.get(url,[data],[fn],[type])

相当于:

$.ajax({
        url:"data.php",
        type:"get",
        data:{},
        success:function () {
            //some code
        },
        dataType:""
    })
2.3 $.post(url,[data],[fn],[type])

相当于:

$.ajax({
        url:"data.php",
        type:"post",
        data:{},
        success:function () {
            //some code
        },
        dataType:""
    })
2.4 $.getScript(url,[callback])

相当于:

$.ajax({
        url:"data.php",
        type:"get",
        data:undefined,
        success:function () {

        },
        dataType:"script"
    })
2.5 $.getJSON(url,[data],[fn])

相当于:

$.ajax({
        url:"data.php",
        type:"get",
        data:undefined,
        success:function () {

        },
        dataType:"json"
    })

3 全局事件

 $("#loading").ajaxStart(function(){
   $(this).show();
 });

4 工具函数

<form action="">
    <label for="username">用户名:</label>
    <input type="text" id="username" name="username">
    <label for="content"></label>
    <textarea id="content" name="content"></textarea>
    <input type="button" value="提交" id="send">
</form>
<script>
$("#send").click(function () {
    $.post("data.php",$("form").serialize(),function (data) {
        console.log($("form").serialize());
        //username=bolala&content=11
        console.log($("form").serializeArray());//对象数组

    })
})
上一篇 下一篇

猜你喜欢

热点阅读