我正在尝试使用 Ajax 将 HTML 代码嵌入到 div
元素中。 (同样,我们使用 iframe 进行操作)。我首先在本地主机上进行测试,以避免同源策略问题。
网络应用程序正在 wamp 服务器上运行。
有2个文件:
- 带有 Ajax 请求的脚本 (index.html):
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div id="testajax" style="width: 500px;height: 300px;border: 1px solid red;top:120px;
position:relative;">
</div>
<script type="text/javascript">
$.ajax({
type: 'POST',
url: 'http://localhost/site.php',
dataType: 'text/html; charset=utf-8',
success: function(response) {
$('#testajax').html(response);
}
});
</script>
</body>
</html>
- 包含我要检索的 html 代码的文件 (site.php):
<?php
header('Access-Control-Allow-Origin: *');
header("content-type:text/html; charset=utf-8");
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="header">This is a header</div>
<div id="main">
<div id="content">This is my main content.</div>
<div id="sidebar">This is a sidebar</div>
</div>
<div id="footer">This is my footer</div>
</body>
</html>
浏览器上没有任何日志或网络错误...所以我看不出这种情况下有什么问题。为什么Ajax成功后从来没有执行过?
最佳答案
简化事情怎么样?
$(document).ready(function() {
$('#testajax').load('http://localhost/site.php', function() {
alert('Load was performed.');
});
});
关于javascript - 无法使用 AJAX localhost 请求 html 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45916641/