#markdown
AJAX (Asynchronous JavaScript and XML) 是一种无需刷新页面即可与服务器交换数据的技术。GET请求通过URL传递参数,适合数据量较小且非敏感信息的场景。
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);
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);
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);
encodeURIComponent
对参数值进行编码原因:未正确编码特殊字符
解决:确保所有参数都经过encodeURIComponent
处理
原因:浏览器的同源策略限制 解决:
原因:异步请求返回顺序不确定 解决:
// 使用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);
}
}
没有搜到相关的沙龙