【问题标题】:Unable to call simple REST web service from ajax无法从 ajax 调用简单的 REST Web 服务
【发布时间】:2013-08-07 04:12:20
【问题描述】:

我正在使用 REST Web 服务开发一个 Web 应用程序。我正在尝试从 ajax 调用简单的 Web 服务。但我没有得到想要的输出。 我的网络服务代码是:

@Path("hello")
public class Hello {

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

我的 ajax 调用 rest web 服务的 html 文件是:

<%@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对象? 谢谢

【问题讨论】:

    标签: html ajax json rest


    【解决方案1】:

    这是正确的做法。

    <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 响应。

    【讨论】:

    • 另外,您忘记导入 jquery.js 源文件。 $.ajax() 是一个 jquery 方法。
    • 我按照你说的做了,我得到了一些响应,Bot 我得到错误 [object object] in error:function(e)
    • 看来,html页面没有问题。这是导致错误的响应。确保您的 REST 服务与响应一起返回正确的状态代码。仅当 ajax 调用返回 HTTP 错误代码时才会调用 error 处理程序。
    • jQuery success 处理程序仅在 HTTP 状态代码为 200 时被调用。除非它从您的 REST 服务接收到 200,否则它将无法工作。
    猜你喜欢
    • 2011-08-28
    • 2015-03-17
    • 1970-01-01
    • 2013-07-22
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    相关资源
    最近更新 更多