跨域访问是一种常见的网络编程问题,如果需要通过Ajax实现跨域访问,可以使用JSONP技术或者跨域资源共享(CORS)技术。对于回调函数的问题,可以使用Promise来处理。使用Promise可以将异步操作封装成一个可控的同步操作,避免回调函数嵌套带来的代码难以维护的问题。例如:
function fetchData(url){
return new Promise((resolve,reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(xhr.statusText);
}
};
xhr.onerror = function() {
reject(xhr.statusText);
};
xhr.send();
})
}
fetchData('http://example.com/api/data')
.then((res) => {
console.log('请求成功:', res);
})
.catch((err) => {
console.log('请求失败:', err);
});