【问题标题】:I wanted to know how can I do get response and post response using ajax and jquery on jsp servlet web project我想知道如何在 jsp servlet web 项目上使用 ajax 和 jquery 获得响应和发布响应
【发布时间】:2018-08-09 03:35:06
【问题描述】:

我想知道如何从 servlet 获取和发布,并在 jsp 页面中使用 jquery ajax 即获取响应并发布它。我已经完成了 doget。如果可能的话,我想从我的 jsp 中删除 jstl页面。请帮助我。提前致谢

这是我的控制器类

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    //get the data from database ie the model class
    try {
        List<Script> scriptitems=modelDBUtil.getScriptList();
        request.setAttribute("scriptItems", scriptitems);
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /*String itemsfood[]={"biriyani","rice"};
    request.setAttribute("itemsfood",itemsfood)*/;



    //redirect to a different page
    RequestDispatcher dispatcher =request.getRequestDispatcher("scriptviewer.jsp");

    dispatcher.forward(request, response); 
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }

}

}

现在我的jsp页面请帮帮我

 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Menu</title>
    </head>
<body>
<p>Script Items</p>

<c:forEach var="items" items="${scriptItems}">


    ${items.id} ${items.command}
</c:forEach>
<form action="appendfile.jsp" method="post">
    <select name="department">
          <c:forEach var="item" items="${scriptItems}">
            <option value="${item.id}">${item.command}</option>
          </c:forEach>
       </select>
       <button type="submit" id="idsubmit">Submit</button>
</form>




</body>
</html> 

【问题讨论】:

  • 您的问题和代码不清楚。你在问什么?你能解释一下你想说什么吗?请花一些时间阅读帮助页面,stackoverflow.com/help/how-to-ask
  • 我已经编辑了...现在

标签: javascript jquery ajax jsp servlets


【解决方案1】:

以下是如何将 json 从 JSP 发送到 Servlete 请参考此代码 与 cmets

  $("#mForm").submit(function(e) {  //your form ID chane it here 
        e.preventDefault();
        var $form = $(this);
        if (!$form.valid()) return false;

        var url = "yourServeleteName";
        $.ajax({
          type: "POST", //the method you want invoke 
          url: "yourServeleteName",  //Add here your servelete name
          data: $("#mForm").serialize(),  //your form ID remove default action from your form
          success: function (data)  //This is to handle if you want any response from Servlete
          {
            alert(data);  //it will alret you message you send from servelete
            //$("#mForm")[0].reset();  /if any form you can reset it option 
          }
        });

      });
    }

【讨论】:

  • 但你没有告诉我如何通过 doPost 中的 gson 解析它
  • 非常感谢您帮助我。并回答每个疑问@v8-E
  • 我没听懂你想说什么,这段代码会将你的所有数据从 JSP 发送到 Servlet,你可以使用 HTML 而不是 JSP,我的建议是使用 HTML 而不是 JSP。此代码也适用于 JSP。如果您的问题是关于解析的,则库不需要这样做,只需下载 Gson Jar 并将其添加到构建路径。阅读更多关于 Gaon,快乐编码
  • 要获取这些值,请使用request.getParameter("exact name of form field you used in JSP")
  • 在运行您的代码时,我没有从表单中的
【解决方案2】:

以下是如何从我的 jsp 页面中删除 jstl 并使其变为 html。

你需要使用这些jquery cdn或者你可以直接使用javascript。

另外,您需要下载 Gson 库才能从 servlet 获得响应。 此代码适用于 get 方法。

您可以这样发送您的itemsfood 到您的html or jsp 将您的doGet 方法修改为:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        List<Script> scriptitems=modelDBUtil.getScriptList();
        request.setAttribute("scriptItems", scriptitems);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    String itemsfood[]={"biriyani","rice"};
    List<String> list = Arrays.asList(itemsfood);
    String json = new Gson().toJson(list);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json); 

}

HTML 或 jsp 代码是:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link
	href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"
	rel="stylesheet" type="text/css" />
<link
	href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"
	rel="stylesheet" type="text/css" />
<link rel='stylesheet' type='text/css'
	href='http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css' />
<link rel="stylesheet"
	href="https://jqueryvalidation.org/files/demo/site-demos.css">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script
	src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script
	src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script
	src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>

<script type="text/javascript">
	$(document).ready(
			function() {
				$.get("appendfile or (add your serveletName here)", function(
						responseJson) {
					var $select = $("#item");
					$select.find("option").remove();
					$.each(responseJson, function(value, key) {
						$("<option>").val(key).text(key).appendTo($select);
					});
				});
			});
</script>
<title>Menu</title>
</head>
<body>
	<form name=myform id="mForm">
		<select name="item" required id="item">
			<option value="Select">select</option>
		</select>
		<button type="submit" id="idsubmit">Submit</button>
	</form>

</body>
</html>

【讨论】:

  • 你能帮我处理一个使用 ajax 的 post 请求吗
  • 是的,为什么不呢,你想用帖子做什么?
  • 是的,我想使用 servlet 在 mysql 数据库中发布表单数据和更新
  • 请帮助@v8-E 我无法在 servlet 的 doPost 方法中发送解析 json 也我想我需要有关如何使用 ajax 从 jsp 页面发送 json 的帮助。谢谢你的帮助跨度>
  • 请找第二个答案
猜你喜欢
  • 2012-08-05
  • 1970-01-01
  • 2011-10-11
  • 2015-03-18
  • 1970-01-01
  • 2016-05-17
  • 1970-01-01
  • 2019-12-01
  • 2011-11-12
相关资源
最近更新 更多