繁体   English   中英

使用Ajax和Jquery加载内容

[英]Content loading with Ajax and Jquery

我希望在页面加载时将一些内容加载到我的div中,但是我希望有一些按钮可以加载新内容,并替换当前DIV中的内容。

这是我的HTML:

<a id="aboutlink" href="#">About</a>
<a id="infolink" href="#">Info</a>
<div id="contentbox">Starting content</div>

这是我的Javascript:

$(document).ready(function(){
    $('#aboutlink').click(function(){
        $('#contentbox').load('/includes/about-info.html');
    });
    $('#testlink').click(function(){
        $('#contentbox').load('/includes/test-info.html');
    });
})

http://jsfiddle.net/spadez/GCg4V/1/

我只是想知道我做错了什么,因为当我在我的服务器上尝试这个时它没有加载任何内容。 我也想知道是否有更好的方法来实现这样的事情,因为它似乎不能对它进行任何加载绑定。

感谢您提供任何帮助或建议。

首先尝试这样的事情:

$.get('/includes/test-info.html', data, function(data){alert(data);})

然后,您将能够确切地看到返回的内容。

如果状态是(200 OK)load方法将只设置第一个匹配元素的html。如果它不是这个,如(404 Not Found)(403 Forbidden) ,那么它将不会设置HTML ..

要设置它而不管响应如何,请尝试我编辑的这个jsFiddle

好吧然后运行此代码来检查那里发生了什么:

<script src="http://code.jquery.com/jquery-latest.min.js"type="text/javascript"></script>

<script>    
    $(document).ready(function () {
        $('#aboutlink').click(function () {
            $('#contentbox').load('/includes/about-info.html', function(response, status, xhr){
                if (status == "error") {
                    var msg = "Sorry but there was an error: ";
                    $("#error").html(msg + xhr.status + " " + xhr.statusText);
                }
            });
        });
        $('#infolink').click(function () {
            $('#contentbox').load('/includes/test-info.html', function(response, status, xhr){
                if (status == "error") {
                    var msg = "Sorry but there was an error: ";
                    $("#error").html(msg + xhr.status + " " + xhr.statusText);
                }
            });
        });

    })  
</script>
<a id="aboutlink" href="#">About</a>
<a id="infolink" href="#">Info</a>
<div id="contentbox">Starting content</div>
<div id="error"></div>

我认为这与你如何指定负载的URL有关。 尝试类似的东西

$(document).ready(function () {
$('#aboutlink').click(function () {
        $('#contentbox').load('includes/about-info.html');
    });
    $('#infolink').click(function () {
        $('#contentbox').load('includes/test-info.html');
    });
})

没有领先的“/”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM