Is it possible to redirect the page with PHP after an Ajax call?

后端 未结 4 713
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 03:57

I have a website where I want to provide an option for users, if they click on a table\'s rows, they get regirected to another page (based on the contect of the table row).

相关标签:
4条回答
  • 2021-01-29 04:12

    You cannot redirect with PHP, however you can easily redirect with the response of your ajax call.

    refer to: window.location.replace(...)

    0 讨论(0)
  • 2021-01-29 04:18

    No.

    A redirect tells the client that the resource they just requested can be found elsewhere.

    The page that was previously loaded which contains that JavaScript is not the resource that the Ajax request is asking for. Something will be returned though—it should get the resource that you redirected to (which will be available in xhr.responseText (assuming the same origin policy doesn't interfere and that you get a 200 OK response at the place you are redirecting to)

    If you intend to always redirect, then don't use Ajax.

    If you intend to sometimes redirect, then you'll need to put the URL in the body of the response, parse it with JavaScript and then assign it to location.

    0 讨论(0)
  • 2021-01-29 04:30

    Yes and no. If you work with jquery, and your ajax call responds with a json like this:

    {
        success : true, 
        redirect_to : "http://www.google.com"
    }
    

    that in php means

    <?php echo json_encode([
        'success' => true,
        'redirect_to' => 'http://www.google.com',
    ]);
    

    then your ajax caller can do the dirty job:

    $.get('/your/path', function (json) {
        if(json.success) {
            document.location.href = json.redirect_to;
        }
    }, 'json');
    

    My two cents.

    0 讨论(0)
  • 2021-01-29 04:34

    I basically want to get the id from the row and when the visitor clicks on the row, they should land on example.php?id=XXXXX

    You can do so entirely from PHP. When you generate the table, in each row (whose id we'll call XXXX to follow your example) you can include a link to example.php?id=XXXXX, or an onclick event for the whole row that executes window.location.href = 'example.php?id=XXXXX';. So your table might look like:

    ...
    <tr onclick="window.location.href = 'example.php?id=1234';">
      <td>1234</td><td>some value</td><td>some other value<td>
    </tr>
    <tr onclick="window.location.href = 'example.php?id=1235';">
      <td>1235</td><td>some value</td><td>some other value<td>
    </tr>
    ...    
    

    It could be done a little nicer by generating the rows with javascript and using event listeners, but this should work.

    0 讨论(0)
提交回复
热议问题