微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用ajax在javascript中调用java类方法?

我有一个 java类::

package MyPackage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.sqlException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.google.gson.Gson;

public class PopulateTextBox {

    Gson gson = new Gson();
    JSONObject obj = new JSONObject();
    JSONArray arr = new JSONArray();
    String temp1;

    String temp;
    List <String>rowValues = new ArrayList<String>();
    List <Integer>rowValues1 = new ArrayList<Integer>();
    String[] contactListNames;
    Connection con=null;
    Statement st=null;
    ResultSet rs=null;


    public String method(){


        try{


        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        Class.forName(driver);

        String db = "jdbc:odbc:Practice_Database";
        con = DriverManager.getConnection(db,"","");

        st = con.createStatement();
        String sql = "SELECT Emp_Name,ID,Email_Add FROM EmployeeSearch";
        rs = st.executeQuery(sql);

        while(rs.next()){
            obj.put("ID",rs.getInt("ID"));
            obj.put("Names",rs.getString("Emp_Name"));
            obj.put("Email",rs.getString("Email_Add"));
            arr.add(obj);

        }
        //obj.accumulate("ID",rowValues1);

        //obj.accumulate("Names",rowValues);
        temp1 = arr.toString();
        System.out.println(temp1);

   }catch(Exception e){System.out.println(e);}
    /*finally{
        try {
                if(con!=null)con.close();
            } catch (sqlException e) {

                e.printstacktrace();
            }
        try {
            if(rs!=null)rs.close();
        } catch (sqlException e) {

            e.printstacktrace();
        }try {
            if(st!=null)st.close();

        } catch (sqlException e) {

            e.printstacktrace();
        }


    }*/
        return temp1;

    }
    public static void main(String args[])
    {
        PopulateTextBox obj = new PopulateTextBox();
        String temp1= obj.method();


    }
}

这是给我一个Json数组.现在我想一次又一次地在JavaScript中调用此类的method()来获取新值,因为我更新了我的数据库.我有一个数据网格工作正常,因为页面第一次加载此json数组中的一组值.但是如何使用Ajax刷新数据.或者如何使用Ajax调用method(),以便在单击页面上的按钮时刷新数据.我在java脚本中调用方法代码是::

<%

    String temp1;
    PopulateTextBox obj = new PopulateTextBox();
    temp1 = obj.method();
    %>

我通过对服务器的Ajax调用在temp1中检索新的值集时遇到问题.请帮忙 ?谢谢.

解决方法

创建一个空白JSP(例如,textBoxAjaxResp.jsp)并从该JSP中输出您的JSON字符串:

<%

String temp1;
PopulateTextBox obj = new PopulateTextBox();
temp1 = obj.method();
%>

<%=temp1 %>

并使用jQuery AJAX调用命中该JSP.

$.get("mypath/textBoxAjaxResp.jsp",function (response) {
    //do operation using the response
},"json");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐