0

テストコードとテスト名の2つの値を持つajaxから応答が来るプログラムを作成します.jspページに3つのテキストフィールドがあります.1つはテストID用です.プログラムを実行し、最初のテキストフィールドにテストID値を入力してタブを押します.テストコードとテスト名が存在するajax応答が来ています。しかし、問題は、2 番目と 3 番目のテキスト フィールドで両方の値 (テスト名、テストコード) が一緒になっていることです。同じフィールドの両方の値ではなく、特定のテスト名を特定のフィールドに移動する必要があります。

コードは次のとおりです。

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(ジャバスクリプト)

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 (データベースからの応答を取得するためのサーブレット)

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));

応答が得られたら、分割を使用してテキストを分割し、次のように両方のフィールドに設定します

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 に答える