we havedone all we c to catch up onwith th

1.We need to come up with a/an ______and make a decision at rmation B.advice C.idea D.news2.Do the dishes,Mike,or I will tell mum.Mind your own_____,Sue.A.action B.duty C.business D.way3.We can see_____full moon on the evening of August______15th every year.A.the.a B.a_百度作业帮
1.We need to come up with a/an ______and make a decision at rmation B.advice C.idea D.news2.Do the dishes,Mike,or I will tell mum.Mind your own_____,Sue.A.action B.duty C.business D.way3.We can see_____full moon on the evening of August______15th every year.A.the.a B.a
A.information B.advice C.idea D.news2.Do the dishes,Mike,or I will tell mum.Mind your own_____,Sue.A.action B.duty C.business D.way3.We can see_____full moon on the evening of August______15th every year.A.the.a B.a.a C.a.the D.the.the追分10
1.选Ccome up with an idea
想一个办法,主意2. 选C mind one's own business 是固定句型,就是“管好你自己”的意思 3.选D “我们每年的8月15都能看见圆圆的月亮”是特指月亮,用the.
此外15th是序数词,前面要加定冠词the
CCD 最后一题是特指圆月,不能用a
您可能关注的推广回答者:Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
I'm using $.post() to call a servlet using Ajax and then using the resulting HTML fragment to replace a div element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the div element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed.
How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?
4,49771828
I read this question and implemented the approach that has been stated regarding setting the response status code to 278 in order to avoid the browser transparently handling the redirects. Even though this worked, I was a little dissatisfied as it is a bit of a hack.
After more digging around, I ditched this approach and used . In this case, all responses to ajax requests have the status code 200 and the body of the response contains a JSON object that is constructed on the server. The javascript on the client can then use the JSON object to decide what it needs to do.
I had a similar problem to yours. I perform an ajax request that has 2 possible responses: one that redirects the browser to a new page and one that replaces an existing HTML form on the current page with a new one. The jquery code to do this looks something like:
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
The JSON object "data" is constructed on the server to have 2 members: data.redirect and data.form. I found this approach to be much better.
5,41521216
I solved this issue by:
Adding a custom header to the response:
public ActionResult Index(){
if (!HttpContext.User.Identity.IsAuthenticated)
HttpContext.Response.AddHeader("REQUIRES_AUTH","1");
return View()
Binding a JavaScript function to the ajaxSuccess event and checking to see if the header exists:
$('body').bind('ajaxSuccess',function(event,request,settings){
if (request.getResponseHeader('REQUIRES_AUTH') === '1'){
window.location = '/';
No browsers handles 301 and 302 responses correctly. And in fact the standard even says they should handle them "transparently" which is a MASSIVE headache for Ajax Library vendors. In
we were forced into using HTTP response status code 278 (just some "unused" success code) to handle transparently redirects from the server...
This really annoys me, and if someone here have some "pull" in W3C I would appreciate that you could let W3C know that we really need to handle 301 and 302 codes ourselves...! ;)
3,04711228
The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function.
For example, our wrapper function was something like:
function cbWrapper(data, funct){
if($("#myForm", data).size() > 0)
top.location.href="login.htm";//redirection
funct(data);
Then, when making the Ajax call we used something like:
$.post("myAjaxHandler",
param1: foo,
param2: bar
function(data){
cbWrapper(data, myActualCB);
This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.
4,49771828
I like Timmerz's method with a slight twist of lemon. If you ever get returned contentType of text/html when you're expecting JSON, you are most likely being redirected. In my case, I just simply reload the page, and it gets redirected to the login page. Oh, and check that the jqXHR status is 200, which seems silly, because you are in the error function, right? Otherwise, legitimate error cases will force an iterative reload (oops)
function (jqXHR, timeout, message) {
var contentType = jqXHR.getResponseHeader("Content-Type");
if (jqXHR.status === 200 && contentType.toLowerCase().indexOf("text/html") &= 0) {
// assume that our login has expired - reload our current page
window.location.reload();
Use the low-level $.ajax() call:
url: "/yourservlet",
data: { },
complete: function(xmlHttp) {
// xmlHttp is a XMLHttpRquest object
alert(xmlHttp.status);
Try this for a redirect:
if (xmlHttp.code != 200) {
top.location.href = '/some/other/page';
15.8k34078
I know this topic is old, but I'll give yet another approach I've found and previously described . Basically I'm using ASP.MVC with WIF (but this is not really important for the context of this topic - answer is adequate no matter which frameworks are used. The clue stays unchanged - dealing with issues related to authentication failures while performing ajax requests).
The approach shown below can be applied to all ajax requests out of the box (if they do not redefine beforeSend event obviously).
$.ajaxSetup({
beforeSend: checkPulse,
error: function (XMLHttpRequest, textStatus, errorThrown) {
document.open();
document.write(XMLHttpRequest.responseText);
document.close();
Before any ajax request is performed CheckPulse method is invoked (the controller method which can be anything simplest):
[Authorize]
public virtual void CheckPulse() {}
If user is not authenticated (token has expired) such method cannot be accessed (protected by Authorize attribute). Because the framework handles authentication, while token expires, it puts http status 302 to the response. If you don't want your browser to handle 302 response transparently, catch it in Global.asax and change response status - for example to 200 OK. Additionally, add header, which instructs you to process such response in special way (later at the client side):
protected void Application_EndRequest()
if (Context.Response.StatusCode == 302
&& (new HttpContextWrapper(Context)).Request.IsAjaxRequest())
Context.Response.StatusCode = 200;
Context.Response.AddHeader("REQUIRES_AUTH", "1");
Finally at the client side check for such custom header. If present - full redirection to logon page should be done (in my case window.location is replaced by url from request which is handled automatically by my framework).
function checkPulse(XMLHttpRequest) {
var location = window.location.
url: "/Controller/CheckPulse",
type: 'GET',
async: false,
beforeSend: null,
function (result, textStatus, xhr) {
if (xhr.getResponseHeader('REQUIRES_AUTH') === '1') {
XMLHttpRequest.abort(); // terminate further ajax execution
window.location =
7,764104996
I think a better way to handle this is to leverage the existing HTTP protocol response codes, specifically 401 Unauthorized.
Here is how I solved it:
Server side: If session expires, and request is ajax. send a 401 response code header
Client side: Bind to the ajax events
$('body').bind('ajaxSuccess',function(event,request,settings){
if (401 == request.status){
window.location = '/users/login';
}).bind('ajaxError',function(event,request,settings){
if (401 == request.status){
window.location = '/users/login';
IMO this is more generic and you are not writing some new custom spec/header.
You also should not have to modify any of your existing ajax calls.
Edit: Per @Rob's comment below, 401 (the HTTP status code for authentication errors) should be the indicator. See
for more detail. With that being said some web frameworks use 403 for both authentication AND authorization errors - so adapt accordingly. Thanks Rob.
I just wanted to share my approach as this might it might help someone:
I basically included a JavaScript module which handles the authentication stuff like displaying the username and also this case handling the redirect to the login page.
My scenario: We basically have an ISA server in between which listens to all requests and responds with a 302 and a location header to our login page.
In my JavaScript module my initial approach was something like
$(document).ajaxComplete(function(e, xhr, settings){
if(xhr.status === 302){
//check for location header and redirect...
The problem (as many here already mentioned) is that the browser handles the redirect by itself wherefore my ajaxComplete callback got never called, but instead I got the response of the already redirected Login page which obviously was a status 200. The problem: how do you detect whether the successful 200 response is your actual login page or just some other arbitrary page??
The solution
Since I was not able to capture 302 redirect responses, I added a LoginPage header on my login page which contained the url of the login page itself. In the module I now listen for the header and do a redirect:
if(xhr.status === 200){
var loginPageRedirectHeader = xhr.getResponseHeader("LoginPage");
if(loginPageRedirectHeader && loginPageRedirectHeader !== ""){
window.location.replace(loginPageRedirectHeader);
...and that works like charm :). You might wonder why I include the url in the LoginPage header...well basically because I found no way of determining the url of GET resulting from the automatic location redirect from the xhr object...
15.8k1066106
I resolved this issue like this:
Add a middleware to process response, if it is a redirect for an ajax request, change the response to a normal response with the redirect url.
class AjaxRedirect(object):
def process_response(self, request, response):
if request.is_ajax():
if type(response) == HttpResponseRedirect:
r = HttpResponse(json.dumps({'redirect': response['Location']}))
return response
Then in ajaxComplete, if the response contains redirect, it must be a redirect, so change the browser's location.
$('body').ajaxComplete(function (e, xhr, settings) {
if (xhr.status == 200) {
var redirect =
redirect = $.parseJSON(xhr.responseText).
if (redirect) {
window.location.href = redirect.replace(/\?.*$/, "?next=" + window.location.pathname);
} catch (e) {
Putting together what Vladimir Prudnikov and Thomas Hansen said:
Change your server-side code to detect if it's an XHR. If it is, set the response code of the redirect to 278.
In django:
if request.is_ajax():
response.status_code = 278
This makes the browser treat the response as a success, and hand it to your Javascript.
In your JS, make sure the form submission is via Ajax, check the response code and redirect if needed:
$('#my-form').submit(function(event){
event.preventDefault();
var options = {
url: $(this).attr('action'),
type: 'POST',
complete: function(response, textStatus) {
if (response.status == 278) {
window.location = response.getResponseHeader('Location')
else { ... your code here ... }
data: $(this).serialize(),
$.ajax(options);
1,50531010
I have a simple solution that works for me, no server code change needed...just add a tsp of nutmeg...
$(document).ready(function ()
$(document).ajaxSend(
function(event,request,settings)
var intercepted_success = settings.
settings.success = function( a, b, c )
if( request.responseText.indexOf( "&html&" ) & -1 )
window.location = window.
intercepted_success( a, b, c );
I check the presence of html tag, but you can change the indexOf to search for whatever unique string exists in your login page...
$(document).ready(function () {
if ($("#site").length & 0) {
window.location = "&%= Url.Content("~") %&" + "Login/LogOn";
Put it on the login page. If it was loaded in a div on the main page, it will redirect til the login page. "#site" is a id of a div which is located on all pages except login page.
Most of the given solutions use a workaround, using an extra header or an inappropiate HTTP code. Those solutions will most probably work but feel a bit 'hacky'. I've come up with another solution.
We're using WIF which is configured to redirect (passiveRedirectEnabled="true") on a 401 response. The redirect is usefull when handling normal requests but won't work for AJAX requests (since browsers won't execute the 302/redirect).
Using the following code in your global.asax you can disable the redirect for AJAX requests:
void WSFederationAuthenticationModule_AuthorizationFailed(object sender, AuthorizationFailedEventArgs e)
string requestedWithHeader = HttpContext.Current.Request.Headers["X-Requested-With"];
if (!string.IsNullOrEmpty(requestedWithHeader) && requestedWithHeader.Equals("XMLHttpRequest", StringComparison.OrdinalIgnoreCase))
e.RedirectToIdentityProvider =
This allows you to return 401 responses for AJAX requests, which your javascript can then handle by reloading the page. Reloading the page
will throw a 401 which will be handled by WIF (and WIF will redirect the user to the login page).
An example javascript to handle 401 errors:
$(document).ajaxError(function (event, jqxhr, settings, exception) {
if (jqxhr.status == 401) { //Forbidden, go to login
//Use a reload, WIF will redirect to Login
location.reload(true);
function showValues() {
var str = $("form").serialize();
$.post('loginUser.html',
function(responseText, responseStatus, responseXML){
if(responseStatus=="success"){
window.location= "adminIndex.html";
I solved this by putting the following in my login.php page.
&script type="text/javascript"&
if (top.location.href.indexOf('login.php') == -1) {
top.location.href = '/login.php';
I didn't have any success with the header solution - they were never picked up in my ajaxSuccess / ajaxComplete method. I used Steg's answer with the custom response, but I modified the JS side some. I setup a method that I call in each function so I can use standard $.get and $.post methods.
function handleAjaxResponse(data, callback) {
//Try to convert and parse object
if (jQuery.type(data) === "string") {
data = jQuery.parseJSON(data);
if (data.error) {
if (data.error == 'login') {
window.location.reload();
else if (data.error.length & 0) {
alert(data.error);
catch(ex) { }
if (callback) {
callback(data);
Example of it in use...
function submitAjaxForm(form, url, action) {
//Lock form
form.find('.ajax-submit').hide();
form.find('.loader').show();
$.post(url, form.serialize(), function (d) {
//Unlock form
form.find('.ajax-submit').show();
form.find('.loader').hide();
handleAjaxResponse(d, function (data) {
// ... more code for if auth passes ...
4,84774781
While the answers seem to work for people if you're using Spring Security I have found extending LoginUrlAuthenticationEntryPoint and adding specific code to handle AJAX more robust.
Most of the examples intercept all redirects not just authentication failures.
This was undesirable for the project I work on.
You may find the need to also extend ExceptionTranslationFilter and override the "sendStartAuthentication" method to remove the caching step if you don't want the failed AJAX request cached.
Example AjaxAwareAuthenticationEntryPoint:
public class AjaxAwareAuthenticationEntryPoint extends
LoginUrlAuthenticationEntryPoint {
public AjaxAwareAuthenticationEntryPoint(String loginUrl) {
super(loginUrl);
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
if (isAjax(request)) {
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Please re-authenticate yourself");
mence(request, response, authException);
public static boolean isAjax(HttpServletRequest request) {
return request != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
Additionally you will probably want to redirect user to the given in headers URL. So finally it will looks like this:
//.... other definition
complete:function(xmlHttp){
if(xmlHttp.status.toString()[0]=='3'){
top.location.href = xmlHttp.getResponseHeader('Location');
UPD: Opps. Have the same task, but it not works. Doing this stuff. I'll show you solution when I'll find it.
2,40111630
in the servlet you should put
response.setStatus(response.SC_MOVED_PERMANENTLY);
to send the '301' xmlHttp status you need for a redirection...
and in the $.ajax function you should not use the .toString() function..., just
if (xmlHttp.status == 301) {
top.location.href = 'xxxx.jsp';
the problem is it is not very flexible, you can't decide where you want to redirect..
redirecting through the servlets should be the best way. but i still can not find the right way to do it.
Based on my brief testing of Firefox, Safari, Opera, IE6/7, it seems the XMLHttpRequest.status does not return the same values and its not compatible across different browsers. I haven't found a more elegant solution.
I just wanted to latch on to any ajax requests for the entire page. @SuperG got me started. Here is what I ended up with:
// redirect ajax requests that are redirected, not found (404), or forbidden (403.)
$('body').bind('ajaxComplete', function(event,request,settings){
switch(request.status) {
case 301: case 404: case 403:
window.location.replace("http://mysite.tld/login");
I wanted to specifically check for certain http status codes to base my decision on. However, you can just bind to ajaxError to get anything other than success (200 only perhaps?) I could have just written:
$('body').bind('ajaxError', function(event,request,settings){
window.location.replace("http://mysite.tld/login");
I was having this problem on a django app I'm tinkering with (disclaimer: I'm tinkering to learn, and am in no way an expert). What I wanted to do was use jQuery ajax to send a DELETE request to a resource, delete it on the server side, then send a redirect back to (basically) the homepage. When I sent HttpResponseRedirect('/the-redirect/') from the python script, jQuery's ajax method was receiving 200 instead of 302. So, what I did was to send a response of 300 with:
response = HttpResponse(status='300')
response['Location'] = '/the-redirect/'
Then I sent/handled the request on the client with jQuery.ajax like so:
&button onclick="*the-jquery*"&Delete&/button&
where *the-jquery* =
type: 'DELETE',
url: '/resource-url/',
complete: function(jqxhr){
window.location = jqxhr.getResponseHeader('Location');
Maybe using 300 isn't "right", but at least it worked just like I wanted it to.
PS :this was a huge pain to edit on the mobile version of SO. Stupid ISP put my service cancellation request through right when I was done with my answer!
2,90111634
You can also hook XMLHttpRequest send prototype. This will work for all sends (jQuery/dojo/etc) with one handler.
I wrote this code to handle a 500 page expired error, but it should work just as well to trap a 200 redirect. Ready the wikipedia entry on
onreadystatechange about the meaning of readyState.
// Hook XMLHttpRequest
var oldXMLHttpRequestSend = XMLHttpRequest.prototype.
XMLHttpRequest.prototype.send = function() {
//console.dir( this );
this.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 500 && this.responseText.indexOf("Expired") != -1) {
document.documentElement.innerHTML = this.responseT
} catch(error) {
// IE makes document.documentElement read only
document.body.innerHTML = this.responseT
oldXMLHttpRequestSend.apply(this, arguments);
If you also want to pass the values then you can also set the session variables and access
In your jsp you can write
&% HttpSession ses = request.getSession(true);
String temp=request.getAttribute("what_you_defined"); %&
And then you can store this temp value in your javascript variable and play around
Another solution I found (especially useful is you want to set a global behaviour) is to use the
together with the . Like others pointed out, don't use a redirect statuscode (3xx), instead use a 4xx statuscode and handle the redirect client-side.
$.ajaxSetup({
statusCode : {
400 : function () {
window.location = "/";
Replace 400 with the statuscode you want to handle. Like others pointed out 401 Unauthorized could be a good idea. I use the 400 since it's very unspecific and I can use the 401 for more specific cases (like wrong login credentials). So instead of redirecting directly your backend should return a 4xx error-code when the session timed out and you do the redirect handling client-side. Works perfect for me even with frameworks like backbone.js
1,25111125
this worked for me:
success: function(data, textStatus, xhr) {
console.log(xhr.status);
on success, ajax will get the same status code the browser gets from the server and execute it.
protected by
Thank you for your interest in this question.
Because it has attracted low-quality answers, posting an answer now requires 10
on this site.
Would you like to answer one of these
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled}

我要回帖

更多关于 catch up tv 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信