简体   繁体   中英

Unable to call simple REST web service from ajax

I am developing an web application using rest web services. I am trying to call the simple web service from the ajax. But I am not getting desired output. My web service code is:

@Path("hello")
public class Hello {

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

and my html file which gives ajax call for rest web service is:

<%@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>

When I call web service from the browser, then my web service gives return value as expected. I call web service from browser as http://localhost:8080/WebApplication4/webresources/hello/first and it return with text "Something happens" What goes wrong here with ajax call? And also How can capture the returned json object in ajax? Thank you

This is the correct way to do it.

<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>

The ajax call has to made from html input type button click event, not on form submit. Form submit event reloads the page and it doesn't wait for ajax response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM