Detecting JSON loaded by browser

I have an application in which most requests are sent through AJAX, although some of them are sent through "regular" HTTP requests. If the request is sent and the user session timeout, the following JSON is returned:

{"authentication":"required"}

The JavaScript function that sends all AJAX requests processes this response by displaying a pop-up message and redirecting the user back to the login page.

However, when a non-AJAX request receives this response, JSON is simply displayed in the browser because the response is processed directly by the browser (i.e. the above JavaScript function is disabled). Obviously, this is not ideal, and I would like non-AJAX requests to receive this answer in order to behave the same as AJAX requests. To achieve this, I can think of two options:

  • Go through the app and convert all requests to AJAX requests. This will work, but can take a long time!

  • The JSON shown above is generated by a very simple JSP. I am wondering if it is possible to add a JavaScript event handler to this JSP that runs just before the content is displayed in the browser? I assume this will never be called for AJAX requests? This handler may invoke other JavaScript code that displays a popup and redirects.

If anyone knows how exactly I can implement the handler that I described in (2), or has any other potential solutions, I would be very grateful if they would pass them on.

Cheers, Don

+3
source share
4 answers

You cannot add a JSP handler this way. Anything you add to it will make it a non-JSON page.

, : , URL , .

URL: http://domain/page.jsp?ajaxRequest=true json

URL: http://domain/page.jsp jsp, .

JSP, -, . AJAX , , .

+1

3) AJAX, GET POST: outputJson=1

+3

4) HTTP- "Accept".

:

.

if(Accept contains application/json...) { // client asking for json, likely  to be XHR
  return {"foo":"bar"}
} else { // other
  return "Location: /login-please";
}
0

:

{"error":"authentication required"}

JSON :

errorHandler({"error":"authentication required"});

script:

function errorHandler(r) {
   alert(r.error);
}

text/javascript, application/x-json.

0

Source: https://habr.com/ru/post/1698981/


All Articles