search

Home  >  Q&A  >  body text

php - Ask about a problem between href, ajax and redirection

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

高洛峰高洛峰2820 days ago606

reply all(7)I'll reply

  • ringa_lee

    ringa_lee2017-05-16 13:01:05

    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.

    reply
    0
  • ringa_lee

    ringa_lee2017-05-16 13:01:05

    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.

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-16 13:01:05

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

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:01:05

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

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-16 13:01:05

    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

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:01:05

    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以外格式數據會執行該方法
        }
    });

    reply
    0
  • ringa_lee

    ringa_lee2017-05-16 13:01:05

    Please modify async and give it a try!

    reply
    0
  • Cancelreply