【问题标题】:Sending Get Request from a jsp file and getting json response从 jsp 文件发送 Get 请求并获取 json 响应
【发布时间】:2020-11-19 03:57:44
【问题描述】:

我想从一个 JSP 文件执行一个 get 请求并显示 json 响应。

获取请求的链接如下所示:

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 的建议(来自 cmets)编写了以下代码:

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

但是,当我单击“调用 Servlet”按钮时,我看不到任何结果。我可以做些什么来纠正它?

我在 ubuntu 18.04 中使用 tomcat。

【问题讨论】:

  • 您可以为此使用 ajax,在 ajax 中调用该 url 并获得响应。
  • @Swati Α在您发表评论后搜索了多种方式,但我无法正确理解我将用我目前所做的更新我的问题

标签: java html jsp tomcat servlets


【解决方案1】:

您可以从 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 字符串。

【讨论】:

  • 我如何在浏览器中显示结果,因为使用 console.log,结果会显示在控制台上。我尝试了 document.write 但它显示为无休止的文本,而不是 json 格式
  • 你需要将数据显示为文本区域中的json字符串吗?
  • 是的,我需要它们在浏览器上以 json 格式显示
  • @iMaCer98 已添加到答案中
猜你喜欢
  • 1970-01-01
  • 2011-07-06
  • 2019-02-23
  • 2020-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多