无法将Ajax发布请求发送到Servlet

编程入门 行业动态 更新时间:2024-10-28 13:17:34
本文介绍了无法将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

本文发布于:2023-10-11 22:13:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1482985.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送到   Ajax   Servlet

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!