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

时间:2015-07-01 18:09:18

标签: java ajax jsp servlets

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

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

这是我的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>

这是我的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.

2 个答案:

答案 0 :(得分:2)

您可以使用$ .post方法来实现此目的。
这是我的解决方案
的index.jsp

sim<-function(df,df1){

y<-df1    
assign(paste(y),data.frame(Var1=numeric(), Var2=numeric(), Var3=numeric(),
                             Var4=numeric()),envir=.GlobalEnv)

colnames(df)[2]<-paste(y)    
assign(paste(y),df,envir=.GlobalEnv)
}

sim(test,"test")  

colnames(test)

<强> GetUserServlet.java

<!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>

答案 1 :(得分:2)

你可以在这里使用$ .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>

,您的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);
  }