本文介绍了无法将Ajax发布请求发送到Servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码.
JavaScript
$(document).ready(function() { $("button").click(function(){ $.post("AjaxpostloginServlet.java", { name:"kevin", pass:"Duckburg" }); }); });Java servlet
package com.iappuniverse.ajaxpostlogin; import java.io.IOException; import javax.servlet.http.*; @SuppressWarnings("serial") public class AjaxpostloginServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException { String name=req.getParameter("name"); System.out.println(name); } }该servlet中的名称不会在控制台中显示.尝试使用ajax .post()将数据发送到服务器,但是无法使链接到ajax .post()调用的servlet运行.
The name here in the servlet doesn't get printed in the console. Trying to send data to the server using ajax .post(), but cannot make the servlet linked to the ajax .post() call run.
推荐答案将您的web.xml更改为以下内容
<?xml version="1.0" encoding="ISO-8859-1" ?> <web-app xmlns="java.sun/xml/ns/j2ee" xmlns:xsi="www.w3/2001/XMLSchema-instance" xsi:schemaLocation="java.sun/xml/ns/j2ee java.sun/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <display-name>Application</display-name> <description> Description Example. </description> <servlet> <servlet-name>login</servlet-name> <servlet-class>AjaxpostloginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app>让我们更进一步,更改您的servlet post方法
lets take it a step further and change your servlet post method
public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException { String name=req.getParameter("name"); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(name); }最终更改ajax调用的网址并使用回调函数.
finally change the url of the ajax call and use a callback function.
$(document).ready(function() { $("button").click(function() { $.post("login",{ name:"kevin", pass:"Duckburg" }).done(function( data ) { alert( "name: " + data ); }) }); });免责声明: 我还没有测试!
更多推荐
无法将Ajax发布请求发送到Servlet
发布评论