这让我疯了几天。我迫切需要帮助。
我有2个文件,index.php和test.php,以及后面的简化版本。
的index.php
<div id="div-hi"></div>
<div id="div-bye"></div>
<script>
$(document).ready(function(){ setInterval(function(){
$( function()
{
$.ajax(
{
url : 'test.php',
type : 'post',
success : function( resp )
{
$('#div-hi').html(resp);
$('#div-bye').html(resp);
}
});return false;}
);}, 1000);});
</script>
test.php的
<div id="hi">
<script type="text/javascript">
---
</script>
</div>
<div id="bye">
<script type="text/javascript">
----
</script>
</div>
我希望index.php中的#div-hi包含来自test.php的#hi和来自index.php的#div-bye的javascript结果,以包含来自test.php的#bye的结果。
我已经没有想法了。请帮忙。
答案 0 :(得分:1)
您的Javascript:
你有一些额外的括号和parens,我不知道return false
在这种情况下做了什么......
setInterval() 的格式为
setInterval( CODE, DELAY);
使用 $.ajax()
的匿名函数:
setInterval( function() { $.ajax( ... ) }, 1000);
此外,return false
通常用于取消jQuery中的defualt行为....它不适用于此。
如果您的回复是HTML,则可以使用 find()
或 context 从中提取div。
尝试这样的事情:
<div id="div-hi"></div>
<div id="div-bye"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
$.ajax(
{
url : 'test.php',
type : 'post',
success : function( resp )
{
// Find the #hi and #bye divs in resp
// and display them in #div-hi and #div-bye
$('#div-hi').html($("#hi", resp).html());
$('#div-bye').html($("#bye", resp).html());
}
});
} , 1000);
});
</script>
(注意几秒后{}
的出现方式)
从页面中提取DIV:
如果您只想将其他页面的片段加载到当前页面,请使用.load()
功能。
例如,如果您在index.php
,并希望从#hi
抓取#bye
和test.php
的内容,并将其显示在#div-hi
中#div-bye
$('#div-hi').load('test.php #hi');
$('#div-bye').load('test.php #bye');
以上是两个电话,但我只想说明.load()
的使用。