Java ajax 将值从 jsp 传递到 servlet

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23485916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:19:05  来源:igfitidea点击:

Java ajax passing values from jsp to servlet

javajqueryajaxjspservlets

提问by fscore

I am trying to pass basic values such as id from jsp to the servlet through ajax. I tried everything but only null is being passed. Even console.log(val)does not print anything to browser console.

我试图通过ajax将诸如id之类的基本值从jsp传递到servlet。我尝试了一切,但只有 null 被传递。甚至console.log(val)不向浏览器控制台打印任何内容。

My understanding is:Web page has form values which onsubmit calls js file. js has ajax which calls the servlet and passes the data of the form. The servlet grabs data from ajax by request.getParameter(val)

我的理解是:网页具有提交时调用js文件的表单值。Node.js 具有调用 servlet 并传递表单数据的 ajax。servlet 从 ajax 中抓取数据request.getParameter(val)

Here is my code:

这是我的代码:

Main.jsp

主程序

<%@ 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>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript">
<script src="js/main.js" type="text/javascript"></script>
</head>
<body>

<form method="post" action="Main" id="firstform">
    <h1>Enter name:</h1>
    <input type="text" name="id" id="id" />
    <input type="submit" name="submit"/>
</form>

</body>
</html>

main.js

主文件

var form = $('#firstform');
console.log("gi");
form.submit(function()
{
    $.ajax({
        url: 'Main',
        data: form.serialize(),
        type: 'post',
        success: function(data){ 
            console.log(data);
        }
            });

    //return false;

});

Main.java

主程序

package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Main
 */
@WebServlet("/Main")
public class Main extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Main() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        int ids;
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String val = request.getParameter("id");
        System.out.print(val);
        if(val != null){
            ids = Integer.parseInt(val);
            out.print(ids); //
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

**Problems:
1)values passed from jsp to servlet
2)console.log doesnt print anything on browser console

**问题:
1)从jsp传递到servlet的值
2)console.log在浏览器控制台上不打印任何东西

1) works but 2) still doesnt.**

1) 有效,但 2) 仍然无效。**

采纳答案by Sanjay Rabari

in main.js type is type: 'post'and you have written code in get method do type:'get'

在 main.js 类型是type: 'post'并且你已经在 get 方法中编写了代码 dotype:'get'

回答by SpringLearner

there is no name attribute in your input field. when you are doing

您的输入字段中没有 name 属性。当你在做

String val = request.getParameter("id"); 

then in servlet then it will search for the input field having name="id"but in your form there is nothing so it will return null;

然后在 servlet 中,它将搜索具有name="id"但在您的表单中没有任何内容的输入字段,因此它将返回null

give name to the input field like

给输入字段命名,如

<input type="text" id="id" name="id"/>

also as sanjayhas said your ajax has type postso change it to getas well

也正如sanjay所说,您的 ajax 有类型帖子,因此也将其更改get

回答by Fares M.

Just for the console.log(data)problem, may be $.ajax()function get confused with response type, try this:

仅针对console.log(data)问题,可能是$.ajax()函数与响应类型混淆,试试这个:

  • Ajax

    $.ajax({
        url: 'Main',
        data: form.serialize(),
        type: 'post',
        dataType:'text/plain',
        success: function(data){ 
            console.log(data);
        }
    });
    
  • Servlet

    response.setContentType("text/plain;charset=UTF-8");
    
  • 阿贾克斯

    $.ajax({
        url: 'Main',
        data: form.serialize(),
        type: 'post',
        dataType:'text/plain',
        success: function(data){ 
            console.log(data);
        }
    });
    
  • 小服务程序

    response.setContentType("text/plain;charset=UTF-8");