【问题标题】:Send and receive data to and from another domain从另一个域发送和接收数据
【发布时间】:2012-05-08 08:07:23
【问题描述】:

我正在尝试编写一个插件。我不能使用任何库或框架。 在任何网站(域)我想从我自己的域启动一个脚本。

例如: 在 domain A 下的网站代码中,我放置了一个从 domain B

开始脚本的代码
<script src="http://domain-b.com/myscript.js" type="text/javascript"></script>

JavaScript 的代码(myscript.js)

type = 'GET';
url = 'http://domain-b.com/echojson.php';
data = ‘var1=1&var2=2’;

_http = new XMLHttpRequest();

_http.open(type, url + '?callback=jsonp123' + '&' + data, true);
_http.onreadystatechange = function() {
      alert(‘Get data: ’ + _http.responseText);
}
_http.send(null);

来自 http://domain-b.com/echojson.php 的脚本总是给出答案:

jsonp123({answer:”answer string”});

但是在 JavaScript 控制台中我看到一个错误 (200) 并且 AJAX 没有得到任何东西。

【问题讨论】:

标签: javascript ajax json xmlhttprequest jsonp


【解决方案1】:

像 LAB、yep/nope 或 Frame.js 这样的脚本加载程序旨在绕过同源策略。他们加载一个脚本文件,因此请求的文件必须如下所示:

response = {answer:”answer string”};

【讨论】:

  • 另外,刚刚注意到,jQuery 在 1.5 版本中添加了一个 crossDomain:true 选项来启用有限的跨域请求。
【解决方案2】:

如果您使用您在此处发布的代码,则它不起作用,因为您在 data 变量中使用了撇号!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多