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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9700055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:22:42  来源:igfitidea点击:

how to call a java class method in javascript using ajax ?

javajavascriptajaxdatagrid

提问by Shantanu Tomar

i have a java class ::

我有一个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();


    }
}

This is returning me a Json array. Now i want to call method() of this class in JavaScript again and again to get new values as i update my database. I have a data grid which is working fine as the page loads for the first time with a set of values in this json array. But how to refresh data using Ajax. Or how to call the method() using Ajax so that data gets refreshed when i click on a button on the page. The code where i am calling this method in java-script is ::

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

<%

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

i am getting problem in retrieving new set of values in temp1 through a Ajax call to the server . please help ? Thanks.

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

采纳答案by Nemoy

Create a blank JSP (for example, textBoxAjaxResp.jsp) and out put your JSON string from that JSP:

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

<%

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

<%=temp1 %>

and hit that JSP using jQuery AJAX call.

并使用 jQuery AJAX 调用点击该 JSP。

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

回答by Premraj

you can use Direct Web Remotinglibrary to call java functions using javascript

您可以使用Direct Web Remoting库使用 javascript 调用 java 函数

But I would suggest to write servlet(tutorial is pretty old but good, you should use servlet 3.0if possible) yourself (instead of using DWR which will have their servlet to write to the response stream also this is very simple requirement so you should write servlet yourself instead of using third party library) and write JSON response directly.

但我建议自己编写servlet(教程很旧但很好,如果可能,您应该使用servlet 3.0)(而不是使用 DWR,它将让他们的 servlet 写入响应流,这也是非常简单的要求,因此您应该编写servlet 而不是使用第三方库)并直接编写 JSON 响应。

回答by david99world

You might want to look at my answer here Updating contents of a jsp page without refreshingthis uses a SpringMVC class which returns a text value from server side to client side using jquery ajax.

您可能想在这里查看我的回答更新 jsp 页面的内容而不刷新它使用 SpringMVC 类,该类使用 jquery ajax 从服务器端返回一个文本值到客户端。