// 服务器端需要设置允许跨域
// 示例(Node.js Express)
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// 确保URL正确
$.ajax({
url: 'https://example.com/api/data', // 检查这个URL是否正确
type: 'GET',
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
<!-- 确保jQuery已正确引入 -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
// 确保事件绑定正确
$(document).ready(function() {
$('#button').click(function() {
$.get('api/data', function(data) {
console.log(data);
});
});
});
// 添加时间戳防止缓存
$.ajax({
url: 'api/data?_=' + new Date().getTime(),
type: 'GET',
// ...
});
// 最简单的测试代码
$.get('api/test', function(data) {
alert('成功: ' + data);
}).fail(function() {
alert('请求失败');
});
如果您能提供更具体的错误现象或代码片段,可以进一步缩小问题范围。