Java 如何在没有提交表单的情况下使用ajax将数据发送到servlet

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31168646/
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-11 10:44:24  来源:igfitidea点击:

How to send data to servlet using ajax without a submitting form

javaajaxjspservlets

提问by Travis

I am new with servlet, I am able to get data from the servlet but not able to send data to it and I want to do this without using a submitting form, can i get some help please

我是 servlet 的新手,我可以从 servlet 获取数据,但无法向它发送数据,我想在不使用提交表单的情况下执行此操作,我可以得到一些帮助吗

on the click of the button it will go to the servlet and return the text but not the value send to it

单击按钮时,它将转到 servlet 并返回文本但不返回发送给它的值

This is my index.jsp

这是我的 index.jsp

<!DOCTYPE html>
<html lang="en">
<head>
    <title>SO question 4112686</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
        $(document).ready(function() {                       
            $('#somebutton').click(function() {               
                $.get('GetUserServlet', function(responseText) { 
                    $('#somediv').text(responseText);        
                });
            });
        });
        $("#somebutton").click(function(){
        $.ajax
        (
        {
            url:'GetUserServlet',
            data:{name:'abc'},
            type:'get',
            cache:false,
            success:function(data){alert(data);},
            error:function(){alert('error');}
        }
    );
}
);
    </script>
</head>
<body>

    <button id="somebutton" onclick="showHint('GetUserServlet.java',   'travis');">press here</button>
    <div id="somediv"></div>
</body>

this my servlet

这是我的 servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "Update Sucessful";
String name = request.getParameter("name");


response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write( name + text);       // Write response body.

采纳答案by Nomesh DeSilva

you could either use $.ajax() or $.post here. since you have used $.ajax(). please refer below correction:

你可以在这里使用 $.ajax() 或 $.post 。因为您使用过 $.ajax()。请参考以下更正:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>SO question 4112686</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
        $(document).ready(function() {                       
            $('#somebutton').click(function() {               
                $.get('GetUserServlet', function(responseText) { 
                    $('#somediv').text(responseText);        
                });
            });
        });


        $("#somebutton").click(function(){
         $.ajax({
            url:'GetUserServlet',
            data:{name:'abc'},
            type:'get',
            cache:false,
            success:function(data){
               alert(data);
               $('#somediv').text(responseText); 
            },
            error:function(){
              alert('error');
            }
         }
    );
}
);
    </script>
</head>
<body>

    <button id="somebutton">press here</button>
    <div id="somediv"> </div>
</body>

and your servlet should be:

你的 servlet 应该是:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetUserServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    doPost(request, response);
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    String text = "Update successfull"; //message you will recieve 
    String name = request.getParameter("name");
    PrintWriter out = response.getWriter();
    out.println(name + " " + text);
  }

回答by Anand

You may use $.post method for this purpose.
Here is my solution
index.jsp

为此,您可以使用 $.post 方法。
这是我的解决方案
index.jsp

<!DOCTYPE html><html lang="en">
<head>
   <title>SO question 4112686</title>
   <script src="http://code.jquery.com/jquery-latest.min.js"></script>
   <script>
     $(document).ready(function() {
         $("#somebutton").click(function() {
             servletCall();
         });

     });
     function servletCall() {
         $.post(
             "GetUserServlet", 
             {name : "Message from jsp"}, //meaasge you want to send
             function(result) {
             $('#somediv').html('Here is your result : <strong>' + result + '</strong>'); //message you want to show
         });
     };
   </script>
</head>
<body>
     <button id="somebutton">press here</button>
     <div id="somediv"></div>
</body>
</html>

GetUserServlet.java

获取UserServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String text = "<br>Message from servlet<br>"; //message you will recieve 
    String name = request.getParameter("name");
    PrintWriter out = response.getWriter();
    out.println(text + name);
}
}