2013-04-22 276 views
1

我在Java中的本地主機上製作了一個RESTful Web服務。當我在我的導航地址欄中輸入以下網址:使用jQuery調用Restful Web服務ajax

http://localhost:8080/GeonotesApp2-war/webresources/route/1 

它會給我:

{"rid":"1","routeComment":"hhhahahahah","routeDateCreate":"2012-04-03T00:00:00+02:00","routeDistance":"13400.0","routeName":"route1","routeUserId":"1"} 

現在我想使用Ajax調用這個腳本得到這個JSON信息:

<html > 
<head> 
    <meta charset="utf-8"> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
    <script> 
    $(function(){ 
     $.ajax({ 
      type: "GET", 
      url: "http://localhost:8080/GeonotesApp2-war/webresources/route/1", 
      dataType: 'json', 
      headers: { 
       Accept: "application/json", 
       "Access-Control-Allow-Origin": "*" 
      }, 
      success: function(resp) { 
       alert("success"); 
      }, 
      error: function(e) { 
       alert("error: "+e); 
      } 
     }); 
    }); 

</script> 
</head> 
<body> 
    Hello Test Service! 
</body> 

但是我總是得到錯誤信息:

error: [object Object] 

我發現這篇文章,並遵循它所做的,但沒有奏效。誰能告訴我爲什麼?由於

Calling Rest webservice using JQuery Ajax call , web service is returning JSON string

+3

更改錯誤處理程序'函數(jqXHR,textStatus,errorThrown)',然後你可以看到什麼實際的錯誤是。你得到的[object Ojbect]是jqXHR對象。 – Marcus 2013-04-22 16:56:58

+1

@G_M我試過更改錯誤處理函數(jqXHR,textStatus,errorThrown),我提醒textStatus,它顯示:error:error,當我提醒errorThrown時,'error:'後沒有任何東西' – stevey 2013-04-22 17:03:44

+0

'jqXHR。 responseText'? – Marcus 2013-04-22 17:06:56

回答

4

的頭必須在服務端。所以瀏覽器知道服務器允許這個網站使用Ajax來加載數據。因此,這些標題:

Access-Control-Allow-Origin: * 
Access-Control-Allow-Methods: GET 

鏈接:

+0

這是CORS的嗎?我從來沒有這樣做...... – 2013-04-22 16:58:08

+0

只有當你從不同的域加載。否則,你會得到一個「安全錯誤」 – Niels 2013-04-22 16:58:34