jquery - 将 arraylist 中的值返回到 ajax 成功函数

标签 jquery ajax jsp servlets arraylist

在ajax成功函数中从数组列表中检索数据。我需要根据通过 ajax 传递的 ID 填充我的文本字段纬度和经度字段。一切正常,但数据未呈现到文本字段。如果执行以下代码,则 success 函数不会返回任何内容。我的代码有什么问题?

FetchData.class

public static ArrayList<Info> getAllInfo(String data_id) {
connection = FetchData.getConnection();
ArrayList<Info> inf = new ArrayList<Info>();
try {
    Statement statement = connection.createStatement();
    ResultSet rs = statement.executeQuery("select * from info_table where data_id='"+data_id"'");

    while(rs.next()) {  
        Info in=new Info();
        in.setData_id(rs.getString("data_id"));
        in.setLat(rs.getDouble("Lat"));
        in.setLongi(rs.getDouble("Longi"));
        inf.add(in);
    }
} catch (SQLException e) {
    e.printStackTrace();
}

return inf;
  }
}

Servlet 类

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 String dataID=request.getParameter("data_id");
ArrayList<Info> in=new ArrayList<Info>();
in=FetchData.getAllInfo();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(in, new TypeToken<List<Info>>() {}.getType());

JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);

}

我的ajax

$.ajax({
url:'Servleturl?dataID='document.getElementById("#data_id").value;
type:'GET',
dataType:'json',
success:function(data){
$("#lat").val(data.Lat);
$("#longi").val(data.Longi);
}
});
});

index.jsp

<input type="text" id="data_id" onblur=""/>
<input type="text" id="lat"/>
<input type="text" id="longi"/>

最佳答案

谢谢大家的回复。

我终于找到了自己问题的解决方案。希望它对其他人有用。

我编写了以下代码。

$.ajax({
    url:'Servleturl?dataID='document.getElementById("#data_id").value;
    type:'GET',
    dataType:'json',
    success:function(data) {
        document.getElementById("#lat").value=data[0].Lat;
        document.getElementById("#longi").value=data[0].Longi;
    }
});

由于数据是从数组列表返回的,因此应将数据作为数组本身提供以检索值。

谢谢大家的回答。

关于jquery - 将 arraylist 中的值返回到 ajax 成功函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22006545/

相关文章:

java - actionURL 标签在 Liferay 中有什么作用?

javascript - 创建一个 div 并放置它

javascript - 如何使用 PhantomJS 保存 AJAX 请求的内容

jquery - JSON 是如何工作的?如果我执行返回类型为 json 的 jquery $.post ,数据如何返回?

java - 依赖注入(inject) - 使用 <jsp :include>

java - 我的 jsp 找不到我的 servlet,给我一个 404

javascript - 是否可以触发/绑定(bind) jQuery UI 事件?

jquery - 使用 Class 和 CSS 设置边框颜色的 IE8 问题?

jquery-ui - JTable jQuery 与 Spring MVC 3 集成问题

javascript - 支持 AJAX 历史按钮而不会发疯