2014-09-26 111 views
0

在我的项目中,我使用MVC api。 我试图通过AJAX在获得一个完整的URL这(和其他)数据: 网址:http://urlexample.comajax与url返回跨源请求被阻止

这给出一个错误: 交叉起源的请求阻塞

我究竟做错了什么?谁能帮助我? 关于这个问题有很多需要解读的内容,但到目前为止我还是没有解决。

这是我的代码:

<script type="text/javascript"> 
function loadstudentid() { 
    $.ajax({ 
     // url: '/api/AZstudent', // > work fine 
     // url: 'http://<domain>.<subdomain>/api/azstudent', > // Gives te issue 
     cache: false, 
     dataType: 'json', 
     success: function (data) { 
      $(data).each(function (i, item) { 
       $(item).each(function (i, stud) { 
        console.log(stud.id_student); 
       }); 
      }); 

     }, 
     error: function (request, status, error) { 
      console.log('error', error); 

     } 
    }); 
} 

Wy为这方面的工作?

<script type="text/javascript"> 
function doewat() { 
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; 
$.getJSON(flickerAPI, { 
    tags: "mount rainier", 
    tagmode: "any", 
    format: "json" 
}) 
.done(function(data) { 
    $.each(data.items, function(i, item) { 
     $("<img>").attr("src", item.media.m).appendTo("#images"); 
     if (i === 3) { 
      return false; 
     } 
    }); 
}); 
} 
//)(); 

http://api.jquery.com/jquery.getjson/

尝试了以下

jQuery.support.cors = false; 

crossDomain: true, 

和:

var url = 'http://myurl.com/api' 
+0

尝试添加这一个crossDomain:true, – sakir 2014-09-26 11:09:26

+0

[jQuery AJAX跨域]的可能重复(http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain) – 2014-09-26 11:12:59

回答

1

之所以这样工作的:

url: '/api/AZstudent', 

是因为这是一个相对路径,这意味着将解决其当前域

究其原因,另一种是没有(也许是本地主机?) ,这是由于ajax请求源自example.com域> somethingelse.com

由于这将允许用户执行恶意操作,因此这不起作用。

这里有一个更深入的这个阅读: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

0

做到这一点是通过CORS的唯一途径。你可以找到一个关于如何实现它的好教程here

总之,这是(主要)关于服务器,而不是你的JavaScript代码。您需要让服务器将访问控制允许来源设置为您请求的的URL 。如果您无法访问服务器,那么您运气不好 - 您唯一能做的就是让自己的服务器(位于同一个域中)充当代理服务器,请求来自其他服务器的请求,然后通过您结果。

相关问题