Ajax servlet send-recive不能正常工作

时间:2016-11-19 08:29:05

标签: java ajax servlets

我有一个HTML和一个JavaServlet页面(jobSeeker.html和jobSeekerServlet.java)。我尝试将数据发送到servlet,但它不起作用,我不知道为什么。请帮我。这是我的代码: jobSeeker.html

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="defaultScripts.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script>
        function sendData(){
            var sendInfo = {
                searchText:document.getElementById("txtSearch")
            };

            $.ajax({
                type: 'POST',
                url: 'jobSeekerServlet',
                data: sendInfo, 
                dataType: 'json',
                contentType: 'application/.json',
                success: function(data) { 
                    alert(data);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert("error");
                }
            });
        }

    </script>
</head>
<body>

   <form name="jobSeekersForm" method="post" id="jobSeekersForm">
       <input type="text" id="txtSearch" name="txtSearch" placeholder="Keresés" onkeyup="sendData()"><br><br>

jobSeekerServlet.java:

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
       String text = "some text";
       response.setContentType("text/plain");
       response.setCharacterEncoding("UTF-8");
       response.getWriter().write(text);  
    }
}

(我也将此代码写入doPost方法。)

1 个答案:

答案 0 :(得分:1)

  • 检查servlet映射是否正确写入web.xml

请参阅此网址click here