一次深刻的教训。js和java投票界面功能提供 ajax返回前后台代码以及动态的添加input和点击动态添加的input的单击事件

后台代码ajax返回值的封装:

Map resultMap = new HashMap();

PrintWriter    pw = response.getWriter();

resultMap.put("code","WEB-0002");
resultMap.put("message","对不起,您是机构用户,无权投票");
pw.print(JSONObject.fromObject(resultMap).toString());

也可以返回list数据

resultMap.put("code","WEB-0000");
resultMap.put("message","");
resultMap.put("result",subjectOptionList); //---直接写list对象 
resultMap.put("title",surveySubjectBean.getTitle());
pw.print(JSONObject.fromObject(resultMap).toString());

前端接受:

$.ajax({
type: "get",
url:'访问路径',
async : false,
dataType : "json",
success: function(data){
if(data.code == "WEB-0000"){
$("#myform input[type='button']").remove();
jsonData = JSON.stringify(data.result); //----转换成json字符串
json= JSON.parse(jsonData);     //----转换成json对象

//---拼接input 并appendChild在一个表单中显示


for (x in json) { //遍历JSON格式的数组取元素, x代表下标
var form = document.getElementById("myform");  
var input = document.createElement("input");
input.type="button";
input.name=json[x].subjectId;
input.id=json[x].id;
input.value=json[x].content;
input.className="btn1 close mh25";
// input.onclick=function(){
// votesajax(json[x].subjectId,json[x].id)
// }
form.appendChild(input);
}

// 绑定在追加在元苏的父级上面 就可以解决 追加input的点击事件失效 动态的添加input需要下面事件解决
$("#myform").on("click","input",function(){
votesajax(this.name,this.id);
})

原文地址:https://www.cnblogs.com/xzcBY/p/9227956.html