首页 技术文章 jquery

jQuery包含所有方法的完整示例

发布日期: 2024-06-25
FontSize: 【
jQuery包含所有方法的完整示例

jQuery无疑是一个很方法的js框架,本网站在整站都使用了jQuery,无论是特效还是弹窗,又或是异步请求$.ajax。

在使用$.ajax的时候,使用最多的可能是这样的:

$.ajax({
    type: 'POST', // 请求类型,可以是GET、POST、PUT、DELETE等
    url: '', // 请求的URL
    data: { // 发送到服务器的数据
        key1: 'value1',
        key2: 'value2'
    },
    dataType: 'json', // 预期服务器返回的数据类型,可以是xml、html、json等
    timeout: 5000, // 请求超时时间,单位为毫秒
    
    success: function(response, textStatus, jqXHR) {
        // 请求成功时执行的回调函数
        console.log('Success:', response);
    }
});

简单有效,但其实$.ajax请求里面还有许多方法,以下一个比较完整的$.ajax请求示例,以供参考。

$.ajax({
    type: 'POST', // 请求类型,可以是GET、POST、PUT、DELETE等
    url: 'https://example.com/api/data', // 请求的URL
    data: { // 发送到服务器的数据
        key1: 'value1',
        key2: 'value2'
    },
    dataType: 'json', // 预期服务器返回的数据类型,可以是xml、html、json等
    timeout: 5000, // 请求超时时间,单位为毫秒
    beforeSend: function(jqXHR, settings) {
        // 在发送请求之前执行的回调函数
        console.log('Before send');
    },
    success: function(response, textStatus, jqXHR) {
        // 请求成功时执行的回调函数
        console.log('Success:', response);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        // 请求失败时执行的回调函数
        console.log('Error:', textStatus, errorThrown);
    },
    complete: function(jqXHR, textStatus) {
        // 请求完成时(无论成功还是失败)执行的回调函数
        console.log('Complete:', textStatus);
    }
}).done(function(response) {
    // 请求成功时执行的回调函数,与success选项等效
    console.log('Done:', response);
}).fail(function(jqXHR, textStatus, errorThrown) {
    // 请求失败时执行的回调函数
    console.log('Fail:', textStatus, errorThrown);
}).always(function(jqXHR, textStatus) {
    // 请求完成时(无论成功还是失败)执行的回调函数,与complete选项等效
    console.log('Always:', textStatus);
});

注意,jQuery3.0版本弃用了success,error,complete,请分别使用done,fail,always代替。