0

我有一个 Html 表单,我需要使用 jquery 将值传递给 servlet,它会验证信息并返回结果。但是当我尝试使用 jQuery 传递数据时。显示收到的空值的 servlet。

<div class="ulogin">
<h2>Login</h2>
<div id="error"></div>
        <form action="Login" method="post" id="spsignin">
        <input type="text" name="uname" class="text validate[required]" id="name" placeholder="Username"/>
        <input type="password" name="pass" class="text validate[required]" id="password" placeholder="Password"/>
        <input type="submit" value="" id="memberlogin"/>
        </form>
</div>

我的 javascript 文件是

 $(document).ready(function() {

//Stops the submit request
$("#spsignin").submit(function(e){
       e.preventDefault();
});

//checks for the button click event
$("#memberlogin").click(function(e){

        //get the form data and then serialize that
        dataString = $("#spsignin").serialize();
        dataString1 = $("#spsignin").serialize();

        var uname = $("input#name").val();
        var pass = $("input#password").val();
         $.ajax({
            type: "POST",
            url: "Login",
            data:'uname=' +encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass),
            dataType: "json",

            //if received a response from the server
            success: function( data, textStatus, jqXHR) {
                 if(data.success)
                 {
                     $("#error").html("<div><b>success!</b></div>"+data);
                  }
                 //display error message
                 else {
                     $("#error").html("<div><b>Information is Invalid!</b></div>"+data);
                 }
            },

            //If there was no resonse from the server
            error: function(jqXHR, textStatus, errorThrown){
                 console.log("Something really bad happened " + textStatus);
                 $("#error").html(jqXHR.responseText);
            },

            //capture the request before it was sent to server
            beforeSend: function(jqXHR, settings){
                 //disable the button until we get the response
                $('#memberlogin').attr("disabled", true);
            },

            complete: function(jqXHR, textStatus){
                //enable the button
                $('#memberlogin').attr("disabled", false);
            }

        });       
 });
});

servlet 是

  package skypark;

  import java.io.IOException;
  import java.io.PrintWriter;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;

  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 Login
  */
 @WebServlet("/Login")
  public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
Boolean success=true;

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

public static Connection prepareConnection()throws ClassNotFoundException,SQLException
{
    String dcn="oracle.jdbc.OracleDriver";
    String url="jdbc:oracle:thin:@//localhost:1521/skypark";
    String usname="system";
    String pass="tiger";
    Class.forName(dcn);
    return DriverManager.getConnection(url,usname,pass);
}
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    String uname,pass;
    response.setContentType("text/html");
    PrintWriter out=response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");

     uname=request.getParameter("uname");
    pass=request.getParameter("pass");
    Boolean suc;
    try {
        suc = check(uname,pass);
            out.println(suc);
        } catch (ClassNotFoundException | SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    out.flush();
      out.close();
}
   public Boolean check(String uname,String pass) throws SQLException, ClassNotFoundException
   {
 ResultSet rs = null;
 int i=0;
 Connection con=prepareConnection();
 String Query="select uname,email from passmanager where pass=?";
 PreparedStatement ps=con.prepareStatement(Query);

  try
  {
    ps.setString(1,pass);
    rs=ps.executeQuery();

        while(rs.next())
        {
            if (uname.equalsIgnoreCase(rs.getString("uname")) || uname.equalsIgnoreCase(rs.getString("email"))) 
            {
    rs.close();                                                              
            ps.close();                                                            
            ps = null;               con.close();                                                            
         con = null;  
        success=true;
        i=1;
       break;
    }
    }
  }
  catch(Exception e)
      {
      System.out.println(e);
      }

  if(i==0)
  {
      success=false;
  }
return success;

}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    doPost(request,response);
}
  }

我认为错误与jquery有关。请任何人帮助我克服这个...

4

3 回答 3

1

问题在于这一行:

data:'uname=' +encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass)

应该是

data: 'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass)

+注意后面的缺失encodeURIComponent(uname)

于 2013-01-23T11:02:50.917 回答
0

好吧,这个问题已经解决了,但是除了一个一个传递值之外,你可以一次提交整个表单,看看这个。

<script>
    // wait for the DOM to be loaded
    $(document).ready(function() 
    {
        // bind 'myForm' and provide a simple callback function
       $("#tempForm").ajaxForm({
       url:'../calling action or servlet',
       type:'post',
       beforeSend:function()
       {
         alert("perform action before making the ajax call like showing spinner image");
       },
       success:function(e){
        alert("data is"+e);
            alert("now do whatever you want with the data");
       }
       });
    });
</script>

你的形式会是这样的

<form id="tempForm" enctype="multipart/form-data">
<input type="text" name="" id="" />
<input type="text" name="" id="" />
<input type="file" name="" id="" />
</form>

你可以在这里找到插件输入链接描述

于 2013-01-23T11:08:21.877 回答
0

我在您的 Ajax 脚本上发现了一个小错误,您的 & 符号不是字符串的一部分:

data:'uname=' + encodeURIComponent(uname) &'pass=' + encodeURIComponent(pass),

应该

data:'uname=' + encodeURIComponent(uname) + '&pass=' + encodeURIComponent(pass),

如果这不能解决问题,那么您可以检查以下几件事:

  • 检查您的 html 中只有一个 id 为“name”的输入元素
  • 检查您的请求是否转到了您的 servlet 映射上的正确 servlet
  • 检查您没有任何过滤器拦截和修改/重定向请求

除此之外,您的代码看起来不错

于 2013-01-23T11:01:45.470 回答