【问题标题】:Echo <script src= from server via ajax通过 ajax 从服务器回显 <script src=
【发布时间】:2014-03-01 12:23:09
【问题描述】:

如果我这样做:

jQuery.ajax({
    url: 'http://server.com/script.php',
    type: 'POST',
    crossDomain: true,
    data: complete_data,
    complete: function(response, textStatus) {
        if (textStatus === 'success') {
            jQuery('#content > form').html(response.responseText);
        }
    }
});

然后 server.com 上的 script.php 看起来像这样:

我工作的防火墙不允许我在其中发布带有脚本标签的内容,但想象一个 php 脚本将 javascript 脚本标签回显到 URL https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places

然后我得到这个错误

XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://my-local-machine.dev' is therefore not allowed access.

我应该在哪里设置 Access-Control-Allow-Origin 标头以使其正常工作?

【问题讨论】:

    标签: php jquery ajax cross-domain


    【解决方案1】:

    您在 https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false&amp;libraries=places 的 HTTP 标头中设置它,因为您(可能)不是 Google,所以您不能这样做。

    尝试通过 XHR 而不是脚本元素获取脚本可能是由于 jQuery 尝试通过 .html() 处理添加带有脚本元素的 HTML 的方式。使用createElement/appendChild/etc 代替innerHTML 构建你的DOM。

    【讨论】:

    • 不幸的是,我从另一个开发人员那里继承了这个项目,而 script.php 的工作方式只是回显 html,所以我不能真正使用 appendChild 或 createElement。我可以轻松地将脚本标记放在与 javascript 文件所在的服务器相同的服务器上,但最好从运行 script.php 的服务器上执行此操作。有没有其他办法?
    猜你喜欢
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多