简体   繁体   English

Ajax跨域脚本请求

[英]Ajax cross domain script request

I have the following code which is attempting to eval some Javascript returned from an HTTPS URL. 我有以下代码,试图评估从HTTPS URL返回的一些Javascript。 I am running the code locally, on localhost:8080 but the ajax request isn't returning the script, it's coming back as undefined. 我在localhost:8080上本地运行代码,但是ajax请求没有返回脚本,它以未定义的形式返回。

$.ajax({
    crossDomain: true,
    dataType: 'script',
    url: 'https://mysite.io/live?action=isAvailable',
    success: init,
    error: function (jqXHR, textStatus, msg) {
        failure();
    },
    timeout: 2000,
    cache: false
});

function init(data) {
    var isAvailable = undefined;
    eval(data);
    if (isAvailable) {
        chatAvailable();
    } else {
        chatUnavailable();
    }
}

This is the response when I visit the URL in Chrome: [https://mysite.io/live?action=isAvailable]: 这是我在Chrome中访问URL时的响应:[https://mysite.io/live?action=isAvailable]:

Response headers: HTTP/1.1 200 OK content-language: en-US content-type: text/javascript;charset=UTF-8 date: Tue, 19 Nov 2013 05:59:25 GMT p3p: CP="NON CUR OTPi OUR NOR UNI" x-old-content-length: 23 transfer-encoding: chunked 响应标头:HTTP / 1.1 200 OK内容语言:zh-CN内容类型:text / javascript; charset = UTF-8日期:2013年11月19日,星期二,05:59:25 GMT p3p:CP =“ NON CUR OTPi OUR NOR UNI“ x-old-content-length:23传输编码:分块

Response body: var isAvailable = true; 响应正文:var isAvailable = true;

Any ideas why this isn't working when I run this code on my local machine at [http://localhost:8080]? 当我在[http:// localhost:8080]的本地计算机上运行此代码时,为什么不起作用?

You need to enable CORS on your server. 您需要在服务器上启用CORS。 Here is a good resource for enabling CORS. 是启用CORS的良好资源。

try something like this 尝试这样的事情

    $.ajax({
        dataType: 'jsonp',
        url: 'https://mysite.io/live?action=isAvailable?callback=?',
        success: init,
        error: function (jqXHR, textStatus, msg) {
            failure();
        },
        timeout: 2000,
        cache: false
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM