javascript - 如果 URL 有 "just one HTML line",jQuery.load() 为什么可以跨域工作?

标签 javascript jquery html ajax

在我的网站上,我尝试编写一个 JavaScript 脚本,在单击按钮时,从某些网站的 HTML 源中抓取数据并在我的网站上显示解析/清理的数据。

阅读后TutorialsPoint's JQuery - Ajax page ,其中展示了 jQuery.load() 方法,

<script type = "text/javascript" language = "javascript">
     $(document).ready(function() {
        $("#driver").click(function(event){
           $('#stage').load('/jquery/result.html');
        });
     });
</script>

我决定在我的网站上尝试一下。我将 URL 从相对 URL 更改为绝对 URL——“http://www.tutorialspoint.com/jquery/result.html”——令我惊讶的是,它实际上正在运行(单击 EXTRACT DATA)。这与我的理解相矛盾,在阅读了数十个 SO 线程以及 jQuery.load() API 后,HTTP 请求将受到同源策略的约束。

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol. ~API

当我将 URL 更改为类似 http://google.com/ 的内容时或 http://www.example.com/脚本不起作用。

前面提到的教程页面上的一行引起了我的注意:

Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading this file, all the content would be populated inside tagged with ID stage. Assuming, our /jquery/result.html file has just one HTML line

如果指定 URL 的 HTML 文件只有一行,load() 如何跨域工作?

最佳答案

这与文件或结构无关。这是关于启用 Cross Origin Request Sharing .如果相关服务器或请求具有以下 header :

Access-Control-Allow-Origin: *

这将使 AJAX 也能够从跨域中获取文件。

确实,通过 Hurl.it 发送 HTTP GET 请求,例如,确认 header 存在。

Request picture

关于javascript - 如果 URL 有 "just one HTML line",jQuery.load() 为什么可以跨域工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45259412/

相关文章:

javascript - 'yield' 表达式隐式生成 'any' 类型,因为其包含的生成器缺少返回类型注释

javascript - Three.js 使用动画进行光线转换对象选择

javascript - getElementsByClassName,递归,一个参数,无下划线.js

javascript - 编写 JQuery If 语句

jquery - 使用从服务器接收到的 json 值更新多个 div 内容

html - 如何创建具有不同列宽的网格

html - 在悬停时缩放和向左移动时防止闪烁

javascript - 如何计算页面上具有值的输入总数?

php - 如何在html表格中创建水平滚动条?

php - 控制 PHP Echo 语句的位置