ajax实现页面请求jsp数据,有大神能给写个例子么?

2024-11-01 10:25:23
有4个网友回答
网友(1):















/*

$(function(){
$(":text[name=name]").keyup(function(){
var val = this.value;
$.get("abc",{"username":val,"age":123},callback);
});
});
function callback(data){

mydiv.innerHTML = data;
}

*/

$(function(){
$("table").attr("align","center");
$(":text[name=name]").keyup(function(){
var val = this.value;
$.get("abc",{"username":val},function(data){
mydiv.innerHTML =data;
$("#mydiv>div").mouseover(function(){
$(this).css("background-color","yellow");
$(":text[name=name]").val($(this).html());
}).mouseout(function(){
$(this).css("background-color","white");
}).click(function(){
$(":text[name=name]").val($(this).html());
$("#mydiv").html("");
});
});
});

});

package com.ajax.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ajax.dao.Dao;

public class ShwServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();

String name = request.getParameter("username");

Dao dao = new Dao();

List list = dao.getList(name);

StringBuffer sf = new StringBuffer();
for(String s : list){

sf.append("
"+s+"
");
}
out.print(sf.toString());

out.flush();
out.close();
}

}

package com.ajax.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class Dao {

private Connection conn = null;
private PreparedStatement pst = null;
private ResultSet rs = null;

private Connection getConn() {
try {
String url = "jdbc:mysql://localhost:3306/mydb";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, "root", "root");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}

public List getList(String name){
List list = new ArrayList();
try {
String sql = "select name from inf where name like '%"+name+"%'";
pst = getConn().prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
list.add(rs.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;

}

}
- ShwServlet com.ajax.web.ShwServlet - ShwServlet /abc - index.jsp

网友(2):

$.ajax({
type:"POST",
url:"${ctx}/stats/energyTrend!getElectricInfo.action",//请求地址
data:{
year:year,
month:month
},//传递参数json格式
dataType:"json",//ajax返回类型还要html/text等
success:function(data){//请求成功data为返回的数据

}
});

网友(3):

HttpServletResponseresponse=ServletActionContext.getResponse();response.setHeader("ContentType","text/json");response.setCharacterEncoding("utf-8");response.getWriter().write(张三);ajax中的msg就是你传过来的值!

网友(4):