简体   繁体   中英

catching a 500 response when setting the src of an iframe

I'm doing something similar to this code:

$('#myIFrame').attr('src', 'dosomethingthatreturnsadocument.aspx');

The page that gets called returns a document, whether that be a word doc, pdf etc and prompts the user to open/save and generally that is working fine.

The problem I have is if something goes wrong at the server side a 500 response is returned. I don't seem to have any way of catching the error.

I've tried a try catch around that line. The .error function of the iframe doesn't seem to catch it.

Does anyone know of a good way that would allow me to catch the 500 so I can act accordingly with the UI?

You should first check the response and then set it in the iframe. You can try something like this:

var loading_url = "/dosomethingthatreturnsadocument.aspx"
$.ajax({
url: loading_url,
type: 'GET',
complete: function(e, xhr, settings){
     if(e.status === 200){
          $('#myIFrame').attr('src', 'dosomethingthatreturnsadocument.aspx');
     }else if(e.status===500){
      // do something
     }
  }
});

You can check the content of the iframe with jQuery immediately after it's loaded and check if it is an error page, by for example checking the title of the page.

$(".loadbutton").on('click',function(){
  $(".iframe").attr("src", "http://www.example.org/")
  .load(function(){
    if($(this).contents().find("title").first().text() == "error"){
      //Error occured!
    }else{
      //Works!
      alert( "loaded!" );
    }
  })
})

You can try to change the if statement to something else you like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM