-1

嗨,我有一个 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(用于在 url 中添加哈希并启用后退按钮并加载内容)

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 从请求的页面加载内容时,这里什么也没有发生!我究竟做错了什么?

4

1 回答 1

1

看起来您在 ajax 响应处理程序中有“#content”...应该是“#pageContent”以匹配 div id。即:

success: function (msg) {
    if (parseInt(msg) != 0) {
        $('#pageContent').html(msg);
        $('#loading').css('visibility', 'hidden');
    }
}
于 2013-09-08T20:09:15.417 回答