簡體   English   中英

無法從Ajax調用簡單的REST Web服務

[英]Unable to call simple REST web service from ajax

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

@Path("hello")
public class Hello {

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

我的html文件給出了對其余Web服務的ajax調用,它是:

<%@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服務將提供預期的返回值。 我從瀏覽器中將Web服務稱為http://localhost:8080/WebApplication4/webresources/hello/first ,它返回的文本為"Something happens"什么"Something happens" 。ajax調用出了什么問題? 還有如何在ajax中捕獲返回的json對象? 謝謝

這是正確的方法。

<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響應。

暫無
暫無

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

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