jQuery sending ajax request to homepage.. if id exists add class to current page
I'm not sure if this is correct way of doing things but hopefully someone will understand. I simply need to send a request to the homepage and check to see if an ID exists, if it exists I need to add a class to an ID on the Current page (or do other jQuery for that matter). I think there is something wrong with my URL because it works fine when im actually ON the homepage.
$(document).ready(function () {
$.ajax({
url: "/",
context: document.body,
success: function(){
if ($('#welcome').length == 1 )
{
$('#login').addClass("do开发者_如何学Cne");
}
}
});
});
The problem is your checking the current page when you do this call,
if ($('#welcome').length == 1 )
so you would only get a true answer if the current page is the home page. What your looking to do is actually check the data that is returned from the ajax call. To do that, your success handler much accept the data that is being passed to it.
success: function(data){
if ($(data).find('#welcome').length >= 1) {
$('#login').addClass("done");
}
}
Since the AJAX request will return what the page echoes as data, you can try just searching that data for the id:
$.ajax({
url: "/",
context: document.body,
success: function(data){
if (data.indexOf('id="welcome"') >= 0) {
$('#login').addClass("done");
}
}
});
However, like @Paramount said, this isn't a good way to check if someone is logged in.
The other thing you could do is create a namespaced 'global' variable (global to your code) that saves the logged in state, e.g
var myjQ {
...
loggedIn : false;
...
}
if myjQ.loggedIn {
// do stuff
} else {
// do other stuff
}
Try:
$(document).ready(function () {
$.ajax({
url: "/",
context: document.body,
success: function(){
if ($(this).find('#welcome').length > 0)
{
$('#login').addClass("done");
}
}
});
});
Or:
$(document).ready(function () {
$.ajax({
url: "/",
context: document.body,
success: function(){
if ($(this).attr('id') == 'welcome')
{
$('#login').addClass("done");
}
}
});
});
Or (using PHP as an example):
<?php
if (isset($loggedin)) {
?>
<script>
$(document).ready(function () {
$('#login').addClass("done");
});
</script>
<?php
}
?>
精彩评论