0

我创建了一个程序,其中响应来自 ajax,它有两个值 testcode 和 testname,我的 jsp 页面中有三个文本字段,一个用于 testid,当我运行程序并在第一个文本字段中输入 testid 值并按 tab 然后ajax 响应即将出现,其中存在 testcode 和 testname。但问题是,在第二个和第三个文本字段中,两个值(testname,testcode)都聚集在一起,我想要一个特定的 testname 去特定的字段,而不是同一个字段中的两个值。

代码是:

index1.jsp(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 type="text/javascript" language="javascript" src="a.js">
    </script>
    </head>
    <body>
    <form  method="post" action="hi">
    test_id:<input type="text" name=testid onblur="mango1(this.value)">
    test code:<input type="text" name="testCode" id="tc">
    testName:<input type="text" name="testName" id="tn">

    <br><input type="submit" value="submit">
    </form>
    <div id="k"> no test name!</div>
    </body>
    </html>

a.js(java脚本)

function mango1(testid)
{
    alert("this is mango1 "+testid);

    var xmlhttp;

    if(window.XMLHttpRequest)
        {

        xmlhttp=new XMLHttpRequest();

        }
    else
        {

        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }


    xmlhttp.onreadystatechange=function()
    {

        if(xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            /*document.getElementById("k").innerHTML=xmlhttp.responseText;*/
            var item=xmlhttp.responseText;
            document.getElementById("tc").value=xmlhttp.responseText;
            document.getElementById("tn").value=xmlhttp.responseText;

            }
            };
            /*xmlhttp.open("POST","hello?testid="+testid, true);*/
            /*xmlhttp.open("POST","hello?testid=", true);*/
            xmlhttp.open("POST","hi?testid="+testid, true);
            xmlhttp.send();

    }

hi.java(用于从数据库获取响应的 servlet)

package one;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;

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

import DAO.TestDao;

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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public hi() {
        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
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        String testid=request.getParameter("testid");
        System.out.println("testid is "+testid);
        /*if(testid.equals("1"))
        {
            out.write("HIV");
        }
        else
        {
            out.write("Urinetest");
        }*/
        TestDao t1=new TestDao();
        Vector vec=t1.getName(testid);

    out.write((String) vec.get(0));

    out.write((String) vec.get(1));
    }

}

testDAo.java(用于数据库操作的 java 文件)

package DAO;

import java.sql.*;
import java.util.Vector;



//import beans.Test;

import DAO.DBCon;

public class TestDao {




    public Vector getName(String testid)
    {
        Connection con=DBCon.getConnection();
         System.out.println("got connection");

        Vector temp=new Vector();

        try
        {
            ResultSet rset=null;
            PreparedStatement pst = con.prepareStatement("select testcode,testname from test where test_id=?");
            System.out.println("got control here");
            pst.setString(1,testid);

            rset=pst.executeQuery();
                 while(rset.next()){ 
                     temp.add(rset.getString(1));

                     temp.add(rset.getString(2));
                     System.out.println("got control here in loop");
                 }
                }
        catch(Exception e)
        {
            e.printStackTrace();
        }
            return  temp;       
        }

    }
4

2 回答 2

1

在like之间使用分隔符

out.write((String) vec.get(0) + ",");

out.write((String) vec.get(1));

当您收到响应时,使用 split 来拆分文本并设置为两个字段,例如

var responseTextVar = xmlhttp.responseText;
var item=responseTextVar.split(',');
document.getElementById("tc").value=item[0];
document.getElementById("tn").value=item[1];
于 2013-05-02T14:20:09.860 回答
0

这是工作正常的完整代码,这是非常简单的方法

<%-- 
    Document   : viewtodata
    Created on : Apr 19, 2014, 12:41:27 PM
    Author     : sohail
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <input type="text" name="uid" value="" id="uid" />
        <input type="text" name="pass" value="" id="pass"/>
        <input type="text" name="2nd" value="" id="2nd" />
        <input type="text" name="3rd" value="" id="3rd" />
         <input type="text" name="4th" value="" id="4th" />
         <input type="text" name="incen" value="" id="incen" />
    </body>
</html>
<script type="text/javascript" src="js/jq.js"></script>
<script type="text/javascript">

    $(document).ready(function() {
        $("#uid").mouseleave(function(e) {
           // e.preventDefault();
            s = $("#uid").val();
           // z = $("#pass").val();
                $.ajax({
                type : "POST",
                url : "FromData?action=pass",
             data : "uid=" + s  ,
              //data : "name=" + s + "&age=" + z ,
             //"name" ye wo parameter name hy jo min nay controller mn req.getpara sy hasil krna hy or s and z mn value ja r hy

                success : function(data) {
                    $('#pass').val(data);
                }
            });
     //return false; 
     });
    });
</script>
<script type="text/javascript" src="js/jq.js"></script>
<script type="text/javascript">

    $(document).ready(function() {
        $("#uid").mouseleave(function(e) {
           // e.preventDefault();
            uid = $("#uid").val();
           // z = $("#pass").val();
                $.ajax({
                type : "POST",
                url : "FromData?action=vin",
             data : "uname=" + uid  ,
              //data : "name=" + s + "&age=" + z ,
             //"name" ye wo parameter name hy jo min nay controller mn req.getpara sy hasil krna hy or s and z mn value ja r hy

                success : function(data) {
                    $('#2nd').val(data);
                }
            });
     //return false; 
     });
    });
</script>
<script type="text/javascript">

    $(document).ready(function() {
        $("#uid").mouseleave(function(e) {
           // e.preventDefault();
            price = $("#uid").val();
           // z = $("#pass").val();
                $.ajax({
                type : "POST",
                url : "FromData?action=price",
             data : "price=" + uid  ,
              //data : "name=" + s + "&age=" + z ,
             //"name" ye wo parameter name hy jo min nay controller mn req.getpara sy hasil krna hy or s and z mn value ja r hy

                success : function(data) {
                    $('#3rd').val(data);
                }
            });
     //return false; 
     });
    });
</script>
<script type="text/javascript">

    $(document).ready(function() {
        $("#incen").mouseleave(function(e) {
           // e.preventDefault();
            incen = $("#incen").val();
           // z = $("#pass").val();
                $.ajax({
                type : "POST",
                url : "FromData?action=incen",
             data : "incen=" + incen  ,
              //data : "name=" + s + "&age=" + z ,
             //"name" ye wo parameter name hy jo min nay controller mn req.getpara sy hasil krna hy or s and z mn value ja r hy

                success : function(data) {
                    $('#4th').val(data);
                }
            });
     //return false; 
     });
    });
</script>       

  /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.servlets.cal;

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 java.util.logging.Level;
import java.util.logging.Logger;

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

/**
 *
 * @author sohail
 */
public class FromData extends HttpServlet {


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ClassNotFoundException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */




       try { 
            String values=request.getParameter("action");
           if(values.equals("pass"))
            {
                String uid=request.getParameter("uid");
           Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ajaxdata","root","sohail");

String sql = " SELECT password FROM login WHERE userID = ? "; 
PreparedStatement pStmt = con.prepareStatement(sql); 
pStmt.setString(1, uid); 
//pStmt.setString(2, upass); 

ResultSet rs = pStmt.executeQuery(); 

String pass; 
if ( rs.next() ) { 
pass = rs.getString("password"); 

// creating a PersonInfo object 



// adding a beanto arraylist 
 out.println(pass);
} // end while 
       }// end of if *********************************************
           else if(values.equals("vin")){
           String uid=request.getParameter("uname");
           Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ajaxdata","root","sohail");

String sql = " SELECT vin FROM login WHERE userID = ? "; 
PreparedStatement pStmt = con.prepareStatement(sql); 
pStmt.setString(1, uid); 
//pStmt.setString(2, upass); 

ResultSet rs = pStmt.executeQuery(); 

String vin; 
if ( rs.next() ) { 
vin = rs.getString("vin"); 

// creating a PersonInfo object 



// adding a beanto arraylist 
 out.println(vin);
} // end while 
           }//end of vin if******************************
           else if(values.equals("price")){
           String pri=request.getParameter("price");
           Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ajaxdata","root","sohail");

String sql = " SELECT price FROM login WHERE userID = ? "; 
PreparedStatement pStmt = con.prepareStatement(sql); 
pStmt.setString(1, pri); 
//pStmt.setString(2, upass); 

ResultSet rs = pStmt.executeQuery(); 

String price; 
if ( rs.next() ) { 
price = rs.getString("price"); 

// creating a PersonInfo object 



// adding a beanto arraylist 
 out.println(price);
} // end while 
           }//end of price if **************************
            else if(values.equals("incen")){
           String incen=request.getParameter("incen");
           Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ajaxdata","root","sohail");

String sql = " SELECT price FROM incentive WHERE incentiveID = ? "; 
PreparedStatement pStmt = con.prepareStatement(sql); 
pStmt.setString(1, incen); 
//pStmt.setString(2, upass); 

ResultSet rs = pStmt.executeQuery(); 

String price; 
if ( rs.next() ) { 
price = rs.getString("price"); 

// creating a PersonInfo object 



// adding a beanto arraylist 
 out.println(price);
} // end while 
           }//end of incen if **************************
       } // end of 2nd try

catch(SQLException sex){ 
System.out.println(sex); 
} //end of catch
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(FromData.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(FromData.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
于 2014-04-19T20:55:53.230 回答