index.jsp
이전 데이터에 데이터를 추가하는 Ajax?
<input type="text" onfocusout="show(this.value)" />
<div id="output"></div>
<script type="text/javascript">
function show(cat)
{
var output = document.getElementById("output");
$.ajax({
type:"get",
url:"fetchdata",
data:"cat="+cat,
success:function(responseJson){
output.innerHTML = responseJson;
}
});
}
fetchdata.java
public class fetchdata extends HttpServlet {
Connection con =null;
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<String> pname = new ArrayList();
ArrayList<String> iname = new ArrayList();
ArrayList<String> cname = new ArrayList();
ArrayList<Double> price = new ArrayList();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String cat = request.getParameter("cat");
PrintWriter out= response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
con= DriverManager.getConnection("jdbc:mysql://localhost:3306/dealtime","root","root");
ps = con.prepareStatement("Select images.product_name,image_name,company_name,price "
+ "from images,products where images.product_name = products.product_name AND "
+ " category_name = ?");
ps.setString(1,cat);
rs=ps.executeQuery();
while(rs.next())
{
pname.add(rs.getString("product_name"));
iname.add(rs.getString("image_name"));
cname.add(rs.getString("company_name"));
price.add(rs.getDouble("price"));
}
String json =new Gson().toJson(pname);
response.setContentType("application/json");
out.println(json);
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(fetchdata.class.getName()).log(Level.SEVERE, null, ex);
}
}
상기 코드는 잘 작동
}
하지만 여러 Ajax 요청이 이루어질 때 데이터 I받은 데이터에 부가되고 이전 아약스 요청에서. 난 그냥 div
새 데이터로 업데이 트하려는뿐만 아니라 응답으로 여러 개체를 보내고 그것에서 값을 추출하는 조작 방법을 알고 싶습니다.
아무 것도 실제로 이해가되지 않습니다. 당신은 HTML로 json 응답을 처리하고'output.innerHTML = responseJson;을 할 때 append가 없으면 이전 html이 대체됩니다 – charlietfl
@charlietfl 예 이전 html을 대체해야하지만 그 이유는 모르겠습니다 똑같다. –
이것을 재현하는 데모를 만드십시오. 또한'show()'의'cat'도 정의되어 있지 않습니다. 브라우저 콘솔에서 오류가 발생하지 않습니까? 표시된 코드가 실패해야합니다. – charlietfl