为什么这个JavaScript调用不会破坏“相同的原始策略”? [英] Why doesn't this JavaScript call break the "same origin policy"
问题描述
我正在使用jQuery显示外部JavaScript文件。原因是同源策略没有被破坏,因为它不是AJAX请求吗?
I'm displaying an external JavaScript file using jQuery. Is the reason "same origin policy" is not being broken because it is not an AJAX request?
小提琴代码:
HTML
HTML
<body>
<div id="toupdate">
<script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/6343621.js"></script>
</div>
</body>
jQuery
jQuery
$(document).ready(function() {
console.log('HTML is '+$('#toupdate').html());
});
推荐答案
哦,这里绝对没问题。您可以从任何地方引用javascript文件。例如,Google CDN提供了常用的js文件,例如你可以使用的jQuery:
Oh absolutely no problem here. You could reference javascript files from wherever you want. For example Google CDN provides common js files such as jQuery that you could use:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
顺便说一下jQuery实现的方式 JSONP 有效。它使用javascript动态地将< script>
标记注入指向某个远程服务器端脚本的DOM:
By the way that's exactly how jQuery's implementation of JSONP works. It uses javascript to inject a <script>
tag dynamically to the DOM pointing to some remote server side script:
<script src="//remotedomain.com/script?callback=abc"></script>
此远程脚本以 Content-Type:'application / x-响应javascript'
回复标题和以下正文:
this remote script responds with a Content-Type: 'application/x-javascript'
response header and the following body:
abc({"foo":"bar"})
在你的域名上你只需定义 abc
功能:
and on your domain you simply define the abc
function:
<script type="text/javascript">
function abc(data) {
alert(data.foo);
}
</script>
然后你去:模拟跨域AJAX(我说模拟因为它不使用本机XHR对象但它实现了相同的效果。)
and there you go: a simulation of a cross domain AJAX (I say simulation because it is not using the native XHR object but it achieves the same effect).
现在您可以理解为什么jQuery的JSONP实现仅限于GET请求=>因为当您注入脚本标记时,浏览器只向其 src
属性发送GET请求。
Now you can understand why jQuery's JSONP implementation is limited to GET requests only => because when you inject a script tag, the browser sends only a GET request to its src
attribute.
这篇关于为什么这个JavaScript调用不会破坏“相同的原始策略”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!