从 jsp 文件发送获取请求并获得 json 响应

Sending Get Request from a jsp file and getting json response

我想从 JSP 文件执行获取请求并显示 json 响应。

get 请求的 link 将如下所示:

https://api.fda.gov/drug/label.json?search="testicular cancer"

但是我想用 html 表单中的输入参数替换搜索参数

html 表格在 index.html 文件中:

 <html>
  <body>
    <form action="login.jsp" method="post">
      <input type="text" name="disease" placeholder="Enter Disease Name"/>
      <input type="submit" value="Submit"/>
    </form>
  </body>
</html>

在 login.jsp 文件中,我根据使用 ajax 的建议(来自评论)编写了以下代码:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript">
       function calling(){
         $.ajax({
            url : 'https://api.fda.gov/drug/label.json?search="testicular cancer"',
            type : 'GET',
            dataType : 'json',// 
            contentType : 'application/json',
            complete : function(response) {
                 console.log(response);  
                }
        });
       }
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <input type="button" value="Call Servlet" name="Call Servlet"  onclick="calling()"/>
</body>
</html>

但是当我点击“Call Servlet”按钮时我看不到任何结果。我该怎么做才能纠正它?

我在 ubuntu 18.04 中使用 tomcat。

您可以从 html 中删除 onClick 并将其添加到 jquery 准备就绪,例如:

$(document).ready(function() {
       $('#callServlet').click(function(){
         $.ajax({
            url : 'https://api.fda.gov/drug/label.json?search="testicular cancer"',
            type : 'GET',
            dataType : 'json',// 
            contentType : 'application/json',
            success: function(response) {
                 console.log(response);  
                }
            error: function(response) {
                 console.log(response);  
                }
        });
       });
});

<input type="button" value="Call Servlet" id="callServlet" />

或者像现在一样在 html 中使用 onClick 触发器,只需确保 ajax.

的成功和错误回调

如果您希望 json 显示在 div 中,其 ID 类似于 result 那么请执行以下操作:

$('#result').html(JSON.stringify(response));

将上述代码添加到 ajax 的成功或错误回调中,以将对 html 的响应添加为 json 字符串。