首页
学习
活动
专区
圈层
工具
发布

带有多个参数的AJAX GET请求,一个URL,结果推入数组

#markdown

多参数AJAX GET请求处理与结果数组存储

基础概念

AJAX (Asynchronous JavaScript and XML) 是一种无需刷新页面即可与服务器交换数据的技术。GET请求通过URL传递参数,适合数据量较小且非敏感信息的场景。

实现方案

1. 原生JavaScript实现

代码语言:txt
复制
let resultArray = [];

function makeGetRequest(url, params) {
    // 构建查询字符串
    const queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&');
    
    const xhr = new XMLHttpRequest();
    const fullUrl = `${url}?${queryString}`;
    
    xhr.open('GET', fullUrl, true);
    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            resultArray.push(JSON.parse(xhr.responseText));
            console.log('Data added to array:', resultArray);
        } else {
            console.error('Request failed with status:', xhr.status);
        }
    };
    xhr.onerror = function() {
        console.error('Request failed');
    };
    xhr.send();
}

// 使用示例
const apiUrl = 'https://api.example.com/data';
const params = {
    page: 1,
    limit: 10,
    sort: 'desc',
    category: 'books'
};

makeGetRequest(apiUrl, params);

2. jQuery实现

代码语言:txt
复制
let resultArray = [];

function makeGetRequest(url, params) {
    $.get(url, params)
        .done(function(data) {
            resultArray.push(data);
            console.log('Data added to array:', resultArray);
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            console.error('Request failed:', textStatus, errorThrown);
        });
}

// 使用示例
const apiUrl = 'https://api.example.com/data';
const params = {
    page: 1,
    limit: 10,
    sort: 'desc',
    category: 'books'
};

makeGetRequest(apiUrl, params);

3. Fetch API实现 (现代推荐方式)

代码语言:txt
复制
let resultArray = [];

async function makeGetRequest(url, params) {
    try {
        const queryString = new URLSearchParams(params).toString();
        const response = await fetch(`${url}?${queryString}`);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        resultArray.push(data);
        console.log('Data added to array:', resultArray);
    } catch (error) {
        console.error('Request failed:', error);
    }
}

// 使用示例
const apiUrl = 'https://api.example.com/data';
const params = {
    page: 1,
    limit: 10,
    sort: 'desc',
    category: 'books'
};

makeGetRequest(apiUrl, params);

关键注意事项

  1. URL长度限制:GET请求有URL长度限制(通常2048字符),参数过多时应考虑POST请求
  2. 参数编码:必须使用encodeURIComponent对参数值进行编码
  3. 缓存问题:GET请求可能被缓存,可添加时间戳参数避免
  4. 缓存问题:GET请求可能被缓存,可添加时间戳参数避免
  5. 并发控制:连续多个请求时,注意数组操作的顺序问题

常见问题解决方案

问题1:参数未正确传递

原因:未正确编码特殊字符 解决:确保所有参数都经过encodeURIComponent处理

问题2:跨域请求失败

原因:浏览器的同源策略限制 解决

  • 服务器端设置CORS头
  • 使用JSONP(仅限GET请求)
  • 配置代理服务器

问题3:数组顺序混乱

原因:异步请求返回顺序不确定 解决

代码语言:txt
复制
// 使用Promise.all处理多个并行请求
async function makeMultipleRequests(requests) {
    try {
        const responses = await Promise.all(requests);
        resultArray = responses; // 按请求顺序排列
    } catch (error) {
        console.error('One or more requests failed:', error);
    }
}

应用场景

  1. 分页加载数据
  2. 多条件筛选查询
  3. 实时数据更新
  4. 批量获取资源信息

优势

  1. 简单易实现
  2. 可被缓存
  3. 便于分享和书签
  4. 对服务器压力较小(相比POST)
代码语言:txt
复制
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的文章

领券