AJAX GET请求提交数据的具体步骤如下:
// 现代浏览器
const xhr = new XMLHttpRequest();
// 兼容旧版IE(如果需要)
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
// IE6及以下
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
GET请求的数据需要附加在URL后面:
const baseUrl = 'https://api.example.com/data';
const params = {
name: '张三',
age: 25,
city: '北京'
};
// 将参数对象转换为URL查询字符串
function objectToQueryString(obj) {
return Object.keys(obj).map(key =>
encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])
).join('&');
}
const queryString = objectToQueryString(params);
const url = `${baseUrl}?${queryString}`;
xhr.open('GET', url, true); // true表示异步请求
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Authorization', 'Bearer token123'); // 如果需要认证
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // 请求完成
if (xhr.status === 200) { // 请求成功
console.log('请求成功:', xhr.responseText);
// 处理响应数据
const data = JSON.parse(xhr.responseText);
} else {
console.error('请求失败:', xhr.status);
}
}
};
// 或者使用更现代的onload/onerror
xhr.onload = function() {
if (xhr.status === 200) {
console.log('成功:', xhr.responseText);
}
};
xhr.onerror = function() {
console.error('请求出错');
};
xhr.send(); // GET请求send()不带参数
function sendGetRequest() {
const xhr = new XMLHttpRequest();
// 准备数据
const params = {
userId: 123,
timestamp: Date.now(),
search: '关键词'
};
// 构建URL
const url = 'https://api.example.com/search?' +
new URLSearchParams(params).toString();
xhr.open('GET', url, true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const response = JSON.parse(xhr.responseText);
console.log('收到响应:', response);
// 处理数据
} catch (error) {
console.error('JSON解析错误:', error);
}
} else {
console.error('请求失败,状态码:', xhr.status);
}
};
xhr.onerror = function() {
console.error('网络错误');
};
// 设置超时
xhr.timeout = 5000; // 5秒超时
xhr.ontimeout = function() {
console.error('请求超时');
};
xhr.send();
}
async function fetchGetRequest() {
const params = { id: 123, name: 'test' };
const url = 'https://api.example.com/data?' +
new URLSearchParams(params).toString();
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
},
// mode: 'cors', // 跨域设置
// cache: 'no-cache' // 缓存控制
});
if (!response.ok) {
throw new Error(`HTTP错误: ${response.status}`);
}
const data = await response.json();
console.log('数据:', data);
return data;
} catch (error) {
console.error('请求失败:', error);
throw error;
}
}
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
data: {
name: '张三',
age: 25
},
dataType: 'json',
success: function(response) {
console.log('成功:', response);
},
error: function(xhr, status, error) {
console.error('失败:', error);
}
});
// 简写形式
$.get('https://api.example.com/data',
{ name: '张三', age: 25 },
function(data) {
console.log('数据:', data);
}
);
// 添加时间戳防止缓存
params._t = Date.now();
编码:参数值需要正确编码(使用encodeURIComponent)
跨域:如果需要跨域,服务器需要设置CORS头
性能:适合获取数据,不适合大量数据提交
建议优先使用Fetch API,它更现代、支持Promise,语法更简洁。