문제

I am using the jQuery UI autocomplete feature for some <input type='text'> boxes where it should return some selections depending on the input. This is working fine but now I need to add a check if the user even is allowed to do this lookup and if not, the user should be alerted.

This is my current code (or some of it at least):

$(this).autocomplete({
  source: function(request,response) {

    $.ajax({
      url: 'search.json',
      data: { field: thisName,
              search: request.term }
    }).done(function(data) {
        response(data);
    }).fail(function(jqXHR, textStatus, errorThrown) {
      console.dir(jqXHR);
      console.log(textStatus);
      console.log(errorThrown);
    });
  },
  minLength: 1,
  ...[CUT]...

If I inside my search.json only has this http_response_code(403); I will receive this in the console (I hope the picture is readable):

Chrome JS console

So my question is - how can I report back an error to the autocomplete script so it acts correctly? For example it could alert the user in some way.

Currently I want to report back with a 403 Forbidden code but there could be other errors too - e.g. the user session could expire or alike. It doesn't necessarily needs to be a HTTP response code but this is what I see as the most correct to use in this scenario?

Please see the JSFiddle demo for my code.

I am using jQuery 1.11.0 and jQuery-UI 1.10.4 together with PHP 5.4 on an IIS 7.5. The IIS will pass .json files as normal PHP files - just to clarify if important.

도움이 되었습니까?

해결책 2

I actually found out that this was caused by me having my own error pages defined in the IIS. When changing the errorcode 403 to someting else (e.g. 999) I will get the 403 error to my Ajax script:

IIS selfdefined errorcodes

Chrome JS console

I have answered this myself in case others are having a similar problem and not being aware that their selfdefined HTML error messages/pages will give a HTTP response code of 200 in the Ajax.

다른 팁

Using AjaxSetup seems to be an option:

$.ajaxSetup({
    error: function (x, status, error) {
        if (x.status == 403) {
            alert("Sorry, your session has expired. Please login again to continue");
            window.location.href ="/Account/Login";
        }
        else {
            alert("An error occurred: " + status + "nError: " + error);
        }
    }
});

Source: http://cypressnorth.com/programming/global-ajax-error-handling-with-jquery/

Since $.ajax() also supports the error method, it might also work for $.ajax() itself.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top