$ .ajax方法不是在调用servlet吗?

时间:2017-03-18 10:26:04

标签: javascript java jquery ajax servlets

我只是通过jsp发送简单参数并通过接收此参数 servlet页面中的javascript并试图通过doGet方法调用servlet的$.ajax()方法,但我的 代码无效。我知道我错了,请纠正我。我使用jsp页面进行输入,使用ajax发送请求和servlet进行请求处理,我没有使用任何jar文件来代替此代码。

的index.jsp:

<script src="js/register.js" type="text/javascript"></script>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>jQuery, Ajax and Servlet/JSP integration example</title>

    <script src="http://code.jquery.com/jquery-1.10.2.js"
        type="text/javascript"></script>
    <script src="js/register.js" type="text/javascript"></script>
    </head>
    <body>

        <form>
            Enter Your Name: <input type="text" id="userName" />
                    <input type="submit" id="editCategory" class="add-new-user" name="btnid" value = "Submit" onclick="send();">

        </form>
        <br>
        <br>

        <strong>Ajax Response</strong>:
        <div id="ajaxGetUserServletResponse"></div>
    </body>
    </html>

register.js:

function send() {
    $.ajax({
        method: "GET",
        url: 'RegisterServlet',

        data: {
            userName: $('#userName').val()
        },
        success: function (responseText) {
            $('#ajaxGetUserServletResponse').text(responseText);
        }
    );
}

RegisterServlet.java:

public class RegisterServlet extends HttpServlet  {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse   response) throws ServletException, IOException {

        String userName = request.getParameter("userName").trim();
        if(userName == null || "".equals(userName)){
            userName = "Guest";
        }

        String greetings = "Hello " + userName;

        response.setContentType("text/plain");
        response.getWriter().write(greetings);
    }
}

1 个答案:

答案 0 :(得分:0)

什么不起作用?

您在输入类型提交中调用onclick我觉得这有点不对。请改用<button>。而且您不需要将其放在<form>标记内。如果你想保持输入类型提交,那么你需要在你的javascript函数中返回false。

问题是您要发送AJAX调用而不是提交表单。因此,请改用<button>标记。

 Enter Your Name: <input type="text" id="userName" />
 <button onclick="send();">

function send() {
    $.ajax({
        method: "GET",
        url: 'RegisterServlet',
        data: {
            userName: $('#userName').val();
        },
        success: function (responseText) {
            $('#ajaxGetUserServletResponse').text(responseText);
        }
    });
    return false;
}