通过jquery加载Ajax,内容未显示

时间:2013-09-08 19:59:47

标签: php javascript jquery html ajax

嗨我有一个html文件,它使用ajax从同一服务器中的其他html文件加载内容。由于某种原因,它不起作用?我不知道因为我是ajax的新手。

这里是index.html(默认主页)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="demo.css" />
<script type="text/javascript" src="../jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head><body><div id="rounded">
<img src="img/top_bg.gif" alt="top" /><div id="main" class="container">
<h1>ajax example</h1>
<h2>ajax jquery</h2>
<ul id="navigation">
<li><a href="#info">Page_1</a></li>
<li><a href="#page2">Page2</a></li>
<li><a href="#page3">Page_3</a></li>
<li><a href="#page4">Page_4</a></li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>
<div class="clear"></div>
<div id="pageContent">
it is a test</div>
</div><div class="clear"></div>
<img src="img/bottom_bg.gif" alt="bottom" /></div>
</body>
</html>

script.js(用于在网址中添加哈希并启用后退按钮以及加载内容)

ar default_content = "";
$(document).ready(function () {
    checkURL();
    $('ul li a').click(function (e) {
        checkURL(this.hash);
    });
    default_content = $('#pageContent').html();
    setInterval("checkURL()", 250);
});
var lasturl = "";

function checkURL(hash) {
    if (!hash) hash = window.location.hash;
    if (hash != lasturl) {
        lasturl = hash;
        if (hash == "")
            $('#pageContent').html(default_content);
        else
            loadPage(hash);
    }
}

function loadPage(url) {
    var datastring = url.replace('#', '');
    $('#loading').css('visibility', 'visible');
    $.ajax({
        type: "POST",
        url: "load_page.php",
        data: 'datastring=' + datastring,
        dataType: "html",
        async: false,
        success: function (msg) {
            if (parseInt(msg) != 0) {
                $('#content').html(msg);
                $('#loading').css('visibility', 'hidden');
            }
        }
    });
}   

和load_page.php

<?php  
$url = $_REQUEST['datastring'];
echo $url;

if(file_exists(''.$url.'.html')){
echo file_get_contents(''.$url.'.html');
}
else{ 
echo 'There is no such page!';
}
?>

需要帮助!正如你所看到的,当ajax调用“pagecontent”时,div会从所请求的页面加载内容,但这里什么也没发生!我做错了什么?

1 个答案:

答案 0 :(得分:1)

看起来你在ajax响应处理程序中有“#content”...应该是'#pageContent'来匹配div id。这就是:

success: function (msg) {
    if (parseInt(msg) != 0) {
        $('#pageContent').html(msg);
        $('#loading').css('visibility', 'hidden');
    }
}