2013-08-07 47 views
0

我正在開發使用其他Web服務的Web應用程序。我正在嘗試從ajax調用簡單的Web服務。但我沒有得到期望的輸出。 我的web服務代碼是:無法從ajax調用簡單的REST Web服務

@Path("hello") 
public class Hello { 

    @GET 
    @Path("/first") 
    @Produces("text/html") 
    public String function1(){ 
    return "Something happens"; 
    } 
} 

和我的HTML文件,該文件提供了Ajax調用了REST Web服務是:

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>JSP Page</title> 
     <script> 
      function callme(){ 
      alert("hello"); 

     $.ajax({ 
      type: "GET", 
      url: "http://localhost:8080/WebApplication4/webresources/hello/first", 
      data:"", 
      dataType:"text", 
      contentType: "text/html", 
      success: function(resp){alert("Server says" + resp);}, 
      error: function(e){ alert("An error has occured");}, 

     }); 
     } 
     </script> 
    </head> 

    <body> 

     <form id="form1" method="GET" onsubmit="callme();"> 
      <input type="text" name="t1"> 
      <input type="submit" Value="SUBMIT"> 
     </form> 
    </body> 
</html> 

當我從瀏覽器中調用Web服務,然後我的web服務提供返回價值如預期。 我打電話給瀏覽器的網絡服務爲http://localhost:8080/WebApplication4/webresources/hello/first ,並返回文本"Something happens" 這裏與ajax調用有什麼問題? 還如何捕獲Ajax中返回的json對象? 謝謝

回答

3

這是正確的方法。

<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>JSP Page</title> 
    <script type="text/javascript" src="jquery.js"></script> 
    <script type="text/javascript"> 
     function callme(){ 
     alert("hello"); 

    $.ajax({ 
     type: "GET", 
     url: "https://localhost/codeTest.php", 
     data:"", 
     dataType:"text", 
     contentType: "text/html", 
     success: function(resp){alert("Server says" + resp);}, 
     error: function(e){ alert("An error has occured");}, 

    }); 
    } 
    </script> 
</head> 

<body> 
    <form id="form1" method="GET"> 
     <input type="text" name="t1"> 
     <input type="button" Value="SUBMIT" onclick="callme();"> 
    </form> 
</body> 

AJAX調用必須從HTML輸入型按鈕單擊事件做出,而不是形式提交。表單提交事件重新加載頁面,並且不會等待Ajax響應。

+0

此外,您忘記了導入jquery.js源文件。 '.ajax()'是一個jQuery方法。 –

+0

我做了你說的,我得到了一些答覆,殭屍我得到錯誤[對象對象]的錯誤:function(e) –

+0

看來,沒有問題的HTML頁面。這是在這裏引起錯誤的迴應。確保您的REST服務與響應一起返回正確的狀態代碼。只有當ajax調用返回HTTP錯誤代碼時,纔會調用'error'處理程序。 –