How to replace the entire html webpage with ajax response?

前端 未结 6 676
难免孤独
难免孤独 2020-12-01 18:38

Before going to the specific question I need to explain a few basic steps.

First, the application in question deals with the management of appointments online by cus

相关标签:
6条回答
  • 2020-12-01 18:47

    if the response is the html content, you can use this line of code:

    ...
    'success': function(response)
           {
               $("body").html(response);
           }
    ...
    

    update:

    this will be hard to replace the html tag, but what you can do:

    ...
    'success': function(response)
           {
               $("html").html($("html", response).html());
           }
    ...
    

    you parse the response with jquery, getting the content of html and replacing the content of the current html

    0 讨论(0)
  • 2020-12-01 18:47

    @JudgeProhet It seems to me that you do not need AJAX request for this purpose. There is no advantage in doing it this way. If the entire page is updated it could be done by an ordinary HTTP request. If you want to use AJAX, you could simply use JavaScript to redirect to new page, which contains appointment details.

    $.ajax({
       'type': 'POST',
       'url': '/backend/ajax_save_appointment',
       'data': postData,
       'success': function(response)
       {
          console.log(response);
          // redirect browser to new location
          window.location.href = '/backend/appointment_details';
       },
       'error': function(xhr, status, error)
       {
          console.log('Error on saving appointment:', xhr, status, error);
          // display error message to the user
       }
    });
    
    0 讨论(0)
  • 2020-12-01 18:51

    Perhaps you can use following code in your 'success'-function to redirect to a different route. window.location.href = 'http://host.local/path/to/appointment-details';

    0 讨论(0)
  • 2020-12-01 18:52

    If your response includes the <head> and <body> tags:

    $("html").html(response);.

    If not, and it's only content, then do:

    $("body").html(response);.

    0 讨论(0)
  • 2020-12-01 19:03

    this question has already been treated here: Replace HTML page with contents retrieved via AJAX

    Basically, you may try (My bad this is not working on IE):

    document.open();
    document.write(newContent);
    document.close();
    

    or, since you are using jquery

    $("body").html(data);
    

    Regards

    0 讨论(0)
  • 2020-12-01 19:08

    I don't have enough reps to leave a comment (!!) but the UPDATE answer by @fribu-smart-solutions (https://stackoverflow.com/a/33914275/1428972) should be marked as the correct one, using:

    $("html").html($("html", response).html());
    

    This fully replaces the page via ajax. This does the job properly whereas others even using "html" doesn't fully work.

    I know this is an old post but it just solved my problem on the same issue! :)

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