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