我想从JSP文件执行获取请求并显示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的建议(根据注释),我编写了以下代码:
<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。
答案 0 :(得分:0)
您可以从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以result
之类的ID显示在div中,请像这样:
$('#result').html(JSON.stringify(response));
将上述代码添加到ajax的成功或错误回调中,以将响应添加为json字符串。