2014-09-26 117 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 。如果您無法訪問服務器,那麼您運氣不好 - 您唯一能做的就是讓自己的服務器(位於同一個域中)充當代理服務器,請求來自其他服務器的請求,然後通過您結果。

相關問題