2011-05-05 40 views
2

我认为这是一个非常简单的问题,但我似乎无法得到它的工作。我需要使用JavaScript(特别是jQuery,显然)从页面抓取一些内容,并将其拉入另一个页面。我已经研究了这一点,但似乎无法得到一个非常简单的例子。非常简单的jQuery .load示例不工作

这里是我试图让内容从页面:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>Test</title> 
</head> 
<body> 
<p>This is the test html page.</p> 
</body> 
</html> 

这里是我试图用拉内容的页面:当我打开

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>PullData</title> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> 
</head> 
<body> 

<ol id="result"></ol> 

<script type="text/javascript"> 
$('#result').load('test.html'); 
</script> 

</body> 
</html> 

页面似乎没有做任何事情。我基本上试图遵循jquery.com中的示例:http://api.jquery.com/load/

这两个html页面都位于C驱动器上某处的相同文件夹中。

我缺少什么?

在此先感谢您的帮助!

回答

5

您使用的浏览器是?

由于同源策略,即使原始文件是以这种方式加载的,某些浏览器也不会允许向file:/// URL发送AJAX请求。我知道Chrome的确如此,但并未测试其他人。

您的​​错误处理程序说什么?呵呵...

+0

我使用Chrome。尝试在Firefox中,它的工作原理(添加结束脚本标签,我在这个例子中失踪)。这是主要问题。谢谢你的帮助! – groovepriest 2011-05-05 14:54:50

+0

不客气。有关详细信息,请参阅http://code.google.com/p/chromium/issues/detail?id=47416 – Alnitak 2011-05-05 15:00:26

3

你的页面末尾有你的脚本标记,这意味着一旦浏览器到达它,就会调用封闭的JS,这可能在DOM准备好之前就会被调用(这意味着<ol>可能不会被设置以获取test.html的内容)。尝试在$(document).ready()回调包围你的负载如下:

<script type="text/javascript"> 
$(document).ready(function() { 
    $('#result').load('test.html'); 
}); 
</script> 

而且你为什么要插入一个完整的HTML页面到有序列表?您应该尝试将HTML代码片段(无头&正文标签)插入内容持有人,如<div><span>,其语义正确。

如果没有这些东西的工作,重视回调如下:

$('#result').load('test.html', null, function(responseText, textStatus, xhr) { 
    alert(textStatus); // see what the response status is 
}); 
0

必须首先检查你的HTML是ready

$(document).ready(function() { 
    $('#result').load('test.html'); 
}); 
0

为了确保#result1被加载,你需要一个document.ready事件处理程序:

<script type="text/javascript"> 
$(document).ready(function(){ 
    $('#result').load('test.html'); 
}); 
</script> 

希望这有助于。干杯

3

这似乎是合乎逻辑的。

检查负载的API,你可能想看看它实际上加载,或者如果它encoutners错误

$("#result").load("/not-here.php", function(response, status, xhr) { 
if (status == "error") { 
    var msg = "Sorry but there was an error: "; 
    $("#result").html(msg + xhr.status + " " + xhr.statusText); 
    } 
}); 

API LINK:http://api.jquery.com/load/

有时调试信息是一个很好的第一步任何解决方案

2

关闭脚本标记在哪里?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> 
</head> 

你的代码需要

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
</head> 
+0

我有两个问题。这是其中之一。当然,我曾多次尝试过这种方式,因为之前我没有把结束标记留在......当我以某种方式问这个问题时,错过了它。谢谢! – groovepriest 2011-05-05 14:53:45