簡體   English   中英

如何使用Ajax從Web API獲取JSON值?

[英]How to fetch json value from web api using ajax?

這可能是一個愚蠢的問題,但我為此感到掙扎,我無法使用ajax從Web api獲取值,請讓我詳細解釋我的問題,我已經使用ajax創建了簡單的Web api,我需要獲取該值,我如何才能實現這一點,讓我發布我的代碼到目前為止我已經嘗試了:

Webapi代碼:

  [EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*")]
        [HttpGet]
        [Route("~/api/getail/{id}/{criteriaid}")]
        public IHttpActionResult GetIncidentByResourceID(int id, int criteriaid)
        {
            IncidentDisplayApiModelCollection collection = objIncidentApiManager.GetDisplayList(id, criteriaid, 4);
            return Json(collection);
        }

這是示例ajax請求:

   <script src="js/jquery-3.2.0.min.js"></script>
              <script >
       $(document).ready(function(){
       $.ajax({
    url: "http://localhost:8080/sf/api/getail/1848/29",
    dataType: "json",
     success: function( response ) {
        console.log( response ); // server response
    },
    error: function( response ) {
        console.log( response ); // server response
    }
});

});
       </script>

在Firefox控制台中得到的是:

Object { readyState: 0, getResponseHeader: .ajax/y.getResponseHeader(), getAllResponseHeaders: .ajax/y.getAllResponseHeaders(), setRequestHeader: .ajax/y.setRequestHeader(), overrideMimeType: .ajax/y.overrideMimeType(), statusCode: .ajax/y.statusCode(), abort: .ajax/y.abort(), state: .Deferred/e.state(), always: .Deferred/e.always(), catch: .Deferred/e.catch(), 9 more… }  index.html:59:9

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/sf/api/getail/1848/29. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

我已經在nuget Manager中下載了cors並添加了confi.enablecors(); 在webapi配置中。 有人可以幫助我如何提前解決此問題!!

origins參數應包含Origin請求標頭的值。

當從帶有file:// URI的頁面發出請求時,瀏覽器將Origin標頭設置為null (字符串)(我已經在Firefox和Chrome中測試過)。

因此,嘗試將“ null”添加到origins參數:

    [EnableCors(origins: "null", headers: "*", methods: "*")]

但我不確定這是否會起作用(如此不同尋常的價值!)

或者,更簡單地說,將其設置為“ *”以允許來自任何來源的請求:

    [EnableCors(origins: "*", headers: "*", methods: "*")]

注意:(!)部署到生產環境時,在允許任何來源的請求之前,請仔細考慮 這意味着實際上任何網站都可以對您的Web API進行AJAX調用。

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM