一般ajax实现跨域请求有两种方法,一种是CORS,见阮一峰老师写的博客,详细易懂(https://blog.csdn.net/liubangbo/article/details/103528895),还有一种是用jsonp的方式实现,这种方式也需要服务器端支持。
在浏览器端用原生JS实现时要注意回调函数的执行上下文一定要为window,这样才能找到此回调函数正确调用。
错误代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSONP实现跨域Ajax请求</title>
</head>
<body>
<div id="mydiv">
<button id="btn">点击</button>
</div>
</body>
<script type="text/javascript">
window.onload = function() {
var oBtn = document.getElementById('btn');
oBtn.onclick = function() {
function handleResponse(response){
console.log(response);
}
var script = document.createElement("script");
script.src = "https://cn.vuejs.org/v2/api/#vm-emit";
document.body.insertBefore(script, document.body.firstChild);
};
};
</script>
</html>
正确代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSONP实现跨域Ajax请求</title>
</head>
<body>
<div id="mydiv">
<button id="btn">点击</button>
</div>
</body>
<script type="text/javascript">
window.onload = function() {
var oBtn = document.getElementById('btn');
oBtn.onclick = function() {
window.handleResponse = function(response){
console.log(response);
}
var script = document.createElement("script");
script.src = "https://cn.vuejs.org/v2/api/#vm-emit";
document.body.insertBefore(script, document.body.firstChild);
};
};
</script>
</html>