<center>ajax同域跨域jsonp函数封装</center>

本文深入解析了一个手写的Ajax函数,详细介绍了其内部工作原理,包括GET和POST请求的处理,JSONP跨域请求,以及如何设置和发送请求参数。同时,文章还探讨了XMLHttpRequest对象的创建和使用,以及如何处理响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function ajax(opt) {
    opt = opt || {};                                     // 对实参处理
    var xmlhttp, method, url, async, dataType, data;
    method = opt.method || 'GET';                        // 默认method为GET
    method = trim(method).toUpperCase();                 //转换成大写并去除空格
    url = opt.url                                        //请求地址
    url = trim(url);
    async = opt.async || true;                           // 默认为异步请求
    dataType = opt.dataType || 'HTML';                   // 设置跨域
    dataType = trim(dataType).toUpperCase();
    data = opt.data || {};                              // 发送参数
    function trim(str) {
        return str.replace(/^\s+|\s+$/g, "");           // 删除左右空格
    };
    var formatParams = function () {                    // 定义格式化参数函数
        if (typeof (data) == "object") {
            var str = "";
            for (var key in data) {
                str += key + "=" + data[pro] + "&";
            }
            data = str.substr(0, str.length - 1);
        }
        if (method == 'GET' || dataType == 'JSONP') {
            if (url.lastIndexOf('?') == -1) {
                url += '?' + data;
            } else {
                url += '&' + data;
            }
        }
    }
    if (window.XMLHttpRequest) {                       // 创建XMLHttpRequest对象
        //Chrome || Firefox
        xmlHttp = new XMLHttpRequest();
    } else {
        //IE
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }                                        
    if (dataType == 'JSONP') {                                                // 跨域请求
        if (typeof (opt.beforeSend) == 'function') opt.beforeSend(xmlHttp);
        var callbackName = ('jsonp_' + Math.random()).replace(".", "");
        var oHeader = document.getElementsByTagName('header')[0];
        data.callback = callbackName;
        var ele = document.createElement('script');
        ele.type = "text/javascript";
        ele.onerror = function () {
            console.log('failed');
            opt.error && opt.error("failed");
        };
        oHeader.appendChild(ele);
        window[callbackName] = function (json) {
            oHeader.removeChild(ele);
            window[callbackName] = null;
            opt.success && opt.success(json);
        };
        formatParams();
        ele.src = url;
        return;
    } else {
        formatParams();
        xmlHttp.open(method, url, async);
        xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");     // 设置响应头
        if (typeof (opt.beforeSend) == 'function') opt.beforeSend(xmlHttp);
        xmlHttp.send(data);                                       // 发送请求
        xmlHttp.onreadystatechange = function () {                 // 响应处理
            if (xmlHttp.status != 200) {
                console.log(xmlHttp.status + 'failed');
                opt.error && opt.error(xmlHttp.status + 'failed');
                return;
            }
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                if (dataType == 'JSON') {
                    try {
                        res = JSON.parse(xmlHttp.responseText);
                    } catch (e) {
                        console.log('json格式错误');
                        opt.error('json格式错误');
                    }
                } else if (dataType == 'XML') {
                    res = xmlHttp.responseXML;
                } else {
                    res = xmlHttp.responseText;
                }
                opt.success && opt.success(res);
            }
        }
    }
}

我的文章列表一地址为https://fcw66.xyz/?thread-1.htm 其中后缀是文章地址二为https://fcw66.xyz/?thread-2.htm 请把下面这个代码绑定到我这个论坛上 这样我就能实现不用后台也可以更新这个代码的文章列表了<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>简约文章列表</title> <style> /* 基础样式 */ * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', sans-serif; } body { background: #f5f5f5; padding: 40px 20px; } /* 容器样式 */ .container { max-width: 800px; margin: 0 auto; background: white; border-radius: 15px; box-shadow: 0 3px 15px rgba(0,0,0,0.1); padding: 30px; } /* 标题样式 */ .title { text-align: center; color: #333; margin-bottom: 30px; font-size: 24px; } /* 文章列表项 */ .article-item { padding: 18px 25px; margin: 10px 0; background: #fff; border: 1px solid #eee; border-radius: 8px; cursor: pointer; transition: all 0.3s; font-size: 16px; } .article-item:hover { transform: translateX(5px); box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-color: #007bff; } /* 分页容器 */ .pagination { display: flex; justify-content: center; margin-top: 30px; gap: 8px; } /* 分页按钮 */ .page-btn { padding: 8px 14px; border: none; background: #f8f9fa; border-radius: 6px; cursor: pointer; transition: all 0.2s; color: #333; } .page-btn.active { background: #007bff; color: white; } .page-btn:hover:not(.active) { background: #e9ecef; } </style> </head> <body> <div class="container"> <h1 class="title">文章列表</h1> <!-- 文章列表 --> <div id="articleList"></div> <!-- 分页按钮 --> <div class="pagination" id="pagination"></div> </div> <script> // 模拟数据(实际使用时替换为真实数据) const allArticles = Array.from({length: 25}, (_, i) => ({ id: i+1, title: `第 ${i+1} 篇文章 - ${'示例标题文本示例标题文本'.slice(0, 15)}` })); let currentPage = 1; const itemsPerPage = 10; // 初始化 function init() { renderArticles(); renderPagination(); } // 渲染文章列表 function renderArticles() { const start = (currentPage - 1) * itemsPerPage; const end = start + itemsPerPage; const currentArticles = allArticles.slice(start, end); const html = currentArticles.map(article => ` <div class="article-item"> ${article.title} </div> `).join(''); document.getElementById('articleList').innerHTML = html; } // 渲染分页按钮 function renderPagination() { const totalPages = Math.ceil(allArticles.length / itemsPerPage); let buttons = ''; for(let i=1; i<=totalPages; i++) { buttons += ` <button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="changePage(${i})"> ${i} </button> `; } document.getElementById('pagination').innerHTML = buttons; } // 切换页面 function changePage(page) { currentPage = page; renderArticles(); renderPagination(); } // 初始化加载 init(); </script> </body> </html>
最新发布
03-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值