一.取属性值
前台页面:
function select(id){
alert("hfdfhdfh"+id);
$.ajax({
url:"selectByid.jsp",
datatype:‘json‘,
data:{id:id}, // 发送数据
error:function(data){
alert("出错了,没有这个学生!!");
},
success:function(data){
alert(data);
var json = eval("("+data+")");//将json类型字符串转换为json对象
alert("hjf"+json.name);
$("#id").val(json.id),
$("#name").val(json.name),
$("#age").val(json.age);
if(json.sex==‘男‘){
$("input:radio[name=‘sex‘]").eq(0).attr("checked",true);
//$("input[name=sex]").attr("checked","checked");
// $("#sex").attr("checked",‘checked‘);
//$("#sex").removeAttr("checked");
}else{
$("input:radio[name=‘sex‘]").eq(1).attr("checked",true);
//$("input[name=sex]").attr("checked","checked");
//$("#sex").attr("checked",‘checked‘);
//$("#sex").removeAttr("checked");
}
}
后台代码:
<%@ page language="java" import="java.util.*,com.dao.*,com.bean.*,com.fasterxml.jackson.databind.ObjectMapper" pageEncoding="utf-8"%>
<%
int id = Integer.parseInt(request.getParameter("id"));
StudentDao dao = new StudentDao();
StudentBean bean = dao.selectByid(id);
if(bean!=null){
ObjectMapper x = new ObjectMapper();
String str = x.writeValueAsString(bean); //将java类对象转换为json字符串
System.out.print(str);
response.getWriter().print(str); //将数据返回前台ajax
}
%>
二.前端ajax接不到json值怎么回事?
前台页面:
function ajaxPost(){
$.ajax({
data:{"name":$("#name").val(),
"age":$("#age").val(),
"sex":$("input[name=‘sex‘]:checked").val()},
type:"Post",
async:false, //加上这个属性就好了
dataType: ‘json‘,
url:"addStudent.jsp",
error:function(data){
alert(‘添加失败!‘);
},
success:function(data){
alert(‘添加成功!‘);
window.location.href = ‘list.jsp‘
}
});
}
后台代码:
<%@ page language="java" import="java.util.*,com.dao.*,com.bean.*" pageEncoding="utf-8"%>
<%
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String sex = request.getParameter("sex");
StudentBean student = new StudentBean();
student.setName(name);
student.setAge(age);
student.setSex(sex);
StudentDao dao = new StudentDao();
int rows = dao.addStudent(student);
if(rows>0){
response.getWriter().print("{}");
}
%>
三.后台查询数据库返回集合,前台显示在表格中。
前台页面:
$(document).ready(function(){
$("#list4").jqGrid({ //jqGrid 表格控件
url:"selectStudent.jsp",
datatype:"json",
mtype:"POST",
height:600,
postData:"{SearchSql:‘‘}",
autowidth:true,
colNames:[‘ID‘,‘姓名‘,‘年龄‘,‘性别‘],
colModel:[
{name:‘id‘,index:‘id‘,hidden:true},
{name:‘name‘,index:‘name‘},
{name:‘age‘,index:‘age‘},
{name:‘sex‘,index:‘sex‘},
],
rownumbers:true,
viewrecords: true,
jsonReader:{
id: "blackId",
repeatitems : false
},
pager:$(‘#gridPager‘)
});
});
后台代码:
<%@ page language="java" import="java.util.*,com.dao.*,com.bean.*,com.fasterxml.jackson.databind.ObjectMapper" pageEncoding="utf-8"%>
<%
StudentDao dao = new StudentDao();
List<StudentBean> list = dao.selectAll();
if(list!=null){
ObjectMapper x = new ObjectMapper();
String str1 = x.writeValueAsString(list); //集合转json类型字符串
response.getWriter().print(str1); //返回前端ajax
}
%>