2016-08-17 48 views
2

我想使用獲取請求調用以下url。jquery:ajax獲取請求不起作用

http://localhost:8080/abc/employees

當我在瀏覽器上面的URL打開,我得到以下答覆。

[{ 「名字」: 「哈日克里希納」, 「ID」:1, 「姓氏」: 「Gurram」, 「permAddrees」:{ 「區域」: 「Marthali」, 「城市」:」班加羅爾「,」國家「,」印度「,」國家「,」卡納塔克邦「,」tempAddrees「:{」area「:」Electronic City「,」city「:」Bangalore「,」country「 ,「state」:「Karnataka」}},{「firstName」:「PTR」,「id」:2,「lastName」:「PTR」,「permAddrees」:{「area」:「Bharath Nagar」城市「:」海得拉巴「,」國家「:」印度「,」國家「:」安得拉 Pradesh「},」tempAddrees「:{」area「:」BTM Layout「,」city「:」Bangalore「國家「:」印度「,」州「:」卡納塔克邦「}}]

以下是我的jquery代碼片段。

<!DOCTYPE html> 
<html> 
    <head> 
     <script src = "jquery-3.1.0.js"></script> 
    </head> 

    <body> 
     <h1>Click the below button to see the AJAX response</h1> 
     <input type="submit" value="click here" id="button1" /> 

     <div id="placeHolder"> 

     </div> 


     <script type="text/javascript"> 
      var jq = jQuery.noConflict(); 

      jq(document).ready(function(){ 
       jq("#button1").click(function(){ 
        alert("Hello"); 
        jq.get("http://localhost:8080/abc/employees", function(data, status){ 
         alert(data + "" + status); 
         jq("#placeHolder").html(response); 
        }); 
       }); 
      }); 
     </script> 
    </body> 
</html> 

當我按一下按鈕,它顯示第一個警告框「警報(‘你好’);」,但不執行回調函數的警告框。任何人都可以幫我找出我的代碼問題。 enter image description here

enter image description here

+0

當你調試這個,怎麼專失敗?服務器的迴應是什麼?有沒有錯誤? – David

+0

嗨大衛,添加屏幕截圖,當你看到標題部分'內容長度是244'即將到來。但是當我去回覆部分時,它是空的。 –

+0

jquery的路徑是否正確? 我檢查過,它在Chrome中運行良好(在給出jQuery的路徑之後)。 – cafebabe1991

回答

1

簡短的回答

Safari允許它和Chrome不允許(CROSS ORIGIN REQUEST共享 - CORS)。

的實驗:

讓我們從這個html file「www.google.com」從我們「localhost」 的執行請求。

在Chrome中會發生什麼?

在鉻中,CORS(CROSS ORIGIN REQUEST SHARING)是不允許的,因此它會阻止你這麼做。

Chrome gives the error as show below for http://www.google.com

Read about it here...

在Safari中會發生什麼?

Safari允許這種行爲,因此是像你想爲你的文件,不是的locahost的一部分,訪問本地主機你從 http://www.google.com

證明I have added url as http://www.google.com, and hence this response comes

+1

明白了。謝謝..:) –