简体   繁体   中英

Javascript - How to check if element with a class exists in a plain string?

In my web project, if a user has been logged out in one browser tab, they will be redirected to login page in any other browser tab after they ineract with that page (click on something, etc.). But, this behaviour would not work if user's click provoke a parent page call in ajax to a child page and render that page on top of itself. The ajax will just return a login page, and it will not be rendered properly on the screen.

I can't determine from a client side whether user is already logged out or not, so I'm trying to implement the following: if a child page that is returned from the server is a login page, do not render it, but redirect the parent page to login page immediately.

$.ajax({
    type: 'GET',
    url: someURL,
    success: function (response) {
    //if a user has been logged out,
    //the response object will contain a string with a rendered html of login page
    //which contains a div with a class "login"
    ...

How do I check if a response contains a div with "login" class? If I do that, I then could just put

window.location.href= "login.asp";

or just

window.location.reload();

if needed.

You could use find like so:

var result = $(response).find('div.login');

if(result.length > 0) {
    //It does contain
}
else {
    //Does not contain
}

Here is the find documentation

You can simply create a jQuery object and do a search on that response object.

$.ajax({
  type: 'GET',
  url: someURL,
  success: function(response) {
    //the response object contains a string with a rendered html of login page
    //which contains a div with a class "login"
    var $page = $(response);
    if ($page.find("div.login").length > 0) {
      //Redirect to the login page
      window.location.href = "login.asp";
    } else {
      window.location.reload();
    }
  }
});

使用正则表达式搜索事件(未经测试):

if (/<div[^>]+?class\s*=\s*"login/.test(response))…

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