从 ajax success 函数中的数组列表中检索数据。我需要根据通过 ajax 传递的 ID 填充我的文本字段纬度和经度字段。一切正常,但数据不会呈现到文本字段。如果执行以下代码,则 success 函数不返回任何内容。我的代码中的 wroong 是什么?
获取数据.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({
url:'Servleturl?dataID='document.getElementById("#data_id").value;
type:'GET',
dataType:'json',
success:function(data){
$("#lat").val(data.Lat);
$("#longi").val(data.Longi);
}
});
});
索引.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;
}
});
由于数据是从数组返回的,因此应该将数据作为数组本身来检索值。
谢谢大家的回答。
输入字段值 <input type="text" id="data_id" onblur=""/>
<input type="text" id="lat" value=""/>
`
'
返回jsonArray.toString()
.如果你不想使用它,你需要输入额外的代码;
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());
response.setContentType("application/json; charset=UTF-8");
PrintWriter printOut = response.getWriter();
JsonArray jsonArray = element.getAsJsonArray();
printOut.print(jsonArray);
printout.flush();
// Or
// printOut.print(jsonArray.toString())
}