javascript - 无法使用 AJAX localhost 请求 html 内容

标签 javascript php jquery ajax

我正在尝试使用 Ajax 将 HTML 代码嵌入到 div 元素中。 (同样,我们使用 iframe 进行操作)。我首先在本地主机上进行测试,以避免同源策略问题。

网络应用程序正在 wamp 服务器上运行。

有2个文件:

  1. 带有 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/

    相关文章:

    Javascript 嵌套循环与 setTimeout

    php - 如何在日志文件中保存xml错误消息?

    php - 尝试将 api 与 native react 连接起来

    javascript - 在一组弹出窗口上显示 Bootstrap 模式

    javascript - 函数的目的而不是值作为 jQuery 中的参数?

    javascript - 如何格式化日期以获得日期和月份的名称?

    javascript - 如何让javascript在Galaxy S3上流畅运行?

    javascript - D3.js:使用鼠标滚轮滚动缩放 x 轴和数据

    javascript - 列出带有复选框的js

    java - 如何将 gps 坐标存储在 mysql 数据库中?