php - Ask about a problem between href, ajax and redirection
高洛峰
高洛峰 2017-05-16 12:59:05
0
7
609

I encountered a problem during development today
The current end directly hrefs an interface (there is redirection code in the interface)
This way you can redirect directly

But when the front end uses ajax to request this interface, it will not be redirected

Why? Please explain the principle

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(7)
左手右手慢动作

ajax itself cannot implement redirection.
You can modify the backend to return the result and execute the page jump after judging it in the callback function of the frontend.
The basic idea is that the backend determines whether the request header contains ajax information
for exampleisAjax = request.getHeader("x-requested-with").equals("XMLHttpRequest");, and then performs different operations according to different requests, such as directly executing a jump or returning the jump url information, and the front end jumps.

左手右手慢动作

My understanding:
The former is the jump of the address, and the latter is the interface for accessing the non-refresh server. How can there be redirection when you only access the interface without making page jumps? Ajax is used without refreshing.

Be sure to jump on the client side. Ajax requests from different browsers will not receive the 3xx status code.

Peter_Zhu

Ajax makes asynchronous requests. You need to determine the status code and perform corresponding operations.

我想大声告诉你

Generally, the results are returned based on the backend and then js jumps

Peter_Zhu

ajax can work normally in the 301 status,
but the premise is that the same origin policy needs to be met!

If you have this need, you can let nginx path proxy to the corresponding URL

我想大声告诉你

ajax originally only interacts with the server for data without refreshing the page (you have to understand the meaning of data interaction). In other words, the client only receives the content output by the server-side index/index/api. The js code and php commands contained in it cannot be executed.
So if you want to redirect, it must be handled by the front end. The following is the correct handling method:

$.ajax({  
    url : "/index/index/api",  
    type : "post",  
    dataType : "json",  
    data: param,  
    success : function(data) {     
       window.location.href = '/index/index';
    },
    error : function() {
        //假如系統接收json以外格式數據會執行該方法
    }
});
左手右手慢动作

Please modify async and give it a try!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template