开发者

jQuery loads the data from PHP but then it disappears, why?

I have searched to see if there is a post similar here and if someone finds it sorry for the duplicate.

So my dilemma is this:

Given the code below, why it my returned data loading and then disappearing?

CSS

#contentbg{
   background-image: url(../images/jp_01.jpg);
   background-repeat: no-repeat;
   background-position: top;
   position: absolute;
   width: 755px;
   height: 629px;
}

#content{
   position: relative;
}

JS

function getHome(){ 
    $.post("php/functions.php?s=home",
     function(data) {
     $('#content').html(data);   
   });
};
开发者_高级运维

HTML

<div id="contentbg">
    <div id="content"></div>
</div>
<ul id="navlist">
     <li id="home"><a href="index.php" onClick="getHome();" title="Home"></a></li>
</ul>

PHP

function displayHome($home){
    if(isset($home)){
        $home = '<img src="images/home.jpg" alt="Home" width="755" height="630" />';
        return $home;
    }
}

if (isset($_GET['s'])) {
    switch ($_GET['s']) {
        case "home": 
            echo displayHome($_GET['s']);
            break;
        }
}

I know that the data gets loaded if I alter the JS as seen below:

function getHome(){ 
    $.post("php/functions.php?s=home",
     function(html) {
     alert("Data Loaded: " + html);
   });
};


The problem is that you are not cancelling the standard action when you click on the link so what is happening is that you click, the javascript gets executed and then index.php gets loaded.

You need to return false from your getHome function to solve this.

function getHome(){ 
   $.post("php/functions.php?s=home",
     function(data) {
     $('#content').html(data);   
   });
   return false;
}

As you are using jquery already, you can also get rid of the inline javascript and use a function like:

$("#home a").click(function(event) {
  event.preventDefault();
  $.post("php/functions.php?s=home",
     function(data) {
     $('#content').html(data);   
  });
);

That assures as well that the standard event (the click on the link) gets cancelled with the first line.


I don't see any item with the id #content in your HTML, are you sure it exists?


I assume #content is defined in your HTML structure:

$('#content').load('php/functions.php?s=home');

Also try removing #content { position: relative; } for now, just incase the content is "jumping" once loaded into the document


There seems to be no "content" div in your html.
Also, use

$("#content").load("url");

as theres no need to use $.post because no post data is being sent.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜