ajax和href 请求后端重定向 解析
关于ajax href请求 处理重定向问题
最近在开发中遇上一个问题 就是ajax 没法正常处理重定向
接下来我们先分析一下代码(这里使用tp5做例子)
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function index()
{
return $this->fetch('Index/index');
}
public function api()
{
header('Location:http://yanghaha.me');
}
}
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/index/Index/api">href重定向</a>
<button id="btn">href重定向</button>
</body>
<script src="./static/jquery.min.js"></script>
<script>
$("#btn").on('click',function () {
$.ajax({
url:'/index/Index/api',
method:'GET',
dataType:'json',
success:function(j){
}
});
})
</script>
</html>
首页我们先运行一下
href 请求的方式
href方式是可以正常重定向的
ajax 方式
首先发现ajax 是没法正常重定向的
再而Request Method: OPTIONS被修改了 控制台报错了 大概意思应该是没法加载重定向地址,被ajax认定为是跨域,事实上的确是跨域
分析代码:
首先我在api方法上根本没有响应 请求 而是直接重定向到一个页面上
也就是说 这样写其实是没有意义的
Ajax本身的意义在于 在不刷新页面的情况下进行数据交换 不做除此之外的处理
也就是不会在本页面去到另外一个页面(重定向,就是不会跳转)
跨域:
上面已经分析到ajax请求一个api 然后这个api内进行了重定向 这样的做法是没意义的
所以即使是用jsonp 也不会得到正确的响应
接下来的问题就是 如果 换成同域下回怎样?
先看修改的代码
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function index()
{
return $this->fetch('Index/index');
}
public function test()
{
return $this->fetch('Index/test');
}
public function api()
{
header('Location:http://yanghaha.me');
}
public function api2()
{
header('Location:http://127.0.0.1:8011/index/Index/test');
}
}
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/index/Index/api">href重定向</a>
<button id="btn">href重定向</button>
</body>
<script src="./static/jquery.min.js"></script>
<script>
$("#btn").on('click',function () {
$.ajax({
url:'/index/Index/api2',
method:'GET',
dataType:'json',
success:function(j){
}
});
})
</script>
</html>
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
测试页面
</body>
</html>
在同源的情况下发现同样是没法正常的跳转到一个网页 ajax没有报错 根据上图不难发现 我们的html被当成字符串输出了
总结下来 ajax无法实现后端的的重定向代码 ajax是在不刷新页面的情况下进行数据交换 已经得到数据后的后续处理
如果要实现ajax跳转 实际上也不难 在前端发起请求就可以了 如以下代码
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/index/Index/api">href重定向</a>
<button id="btn">href重定向</button>
</body>
<script src="./static/jquery.min.js"></script>
<script>
$("#btn").on('click',function () {
$.ajax({
url:'/index/Index/api2',
method:'GET',
dataType:'json',
success:function(j){
window.location.href = "http://127.0.0.1:8011/index/Index/test";
}
});
})
</script>
</html>
如果对您有帮助,您又乐意的话,请多多支持!

