ssm+ajax異步請求返回list遍歷


jsp頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="js/jquery-1.5.js"></script>
<script type="text/javascript">

function findStudentInfo() {
debugger
$.ajax({
type:"get",
url:"${pageContext.request.contextPath}/getemps",
dataType:"json",
success : function (data) {
debugger
$("#showMessageDiv").empty();
$("#showMessageDiv").append("<table id='table1'></table>");
$("#table1").append("<tr><td>員工ID</td><td>姓名</td><td>性別</td><td>郵箱地址</td></tr>");
$.each(data,function (i,result) {
var sex="女"
if (result.gender==1){sex="男"}
var item="<tr><td>"+result.id+"</td><td>"+result.lastName+"</td><td>"+sex+"</td><td>"+result.email+"</td>";
$("#table1").append(item);
});

},
error:function(){
alert("錯誤");
}
});
}

</script>

<body>
<div>
異步請求響應
</div>
<div id="showMessageDiv">
</div>
<div id="data">
<input type="submit" id="getBtn" title="點擊" onclick="findStudentInfo()"/>
</div>
</body>
</html>

2 action

@Controller
public class EmployeeController {

@Autowired
EmployeeService employeeService;

@RequestMapping("/getemps")
@ResponseBody
public String emps() throws JsonGenerationException, JsonMappingException, IOException{
List<Employee> emps = employeeService.getEmps();
ObjectMapper mapper= new ObjectMapper();
String jsonStr = mapper.writeValueAsString(emps );
System.out.println(jsonStr );
return jsonStr;
}

}

 

 轉自:逆水乘舟,不進則退:https://www.cnblogs.com/zhangzhiqin/p/8592396.html

 

關於ajax的簡要說明:

$(function(){
    $.ajax({
        url : 請求的路徑(action),
        type : "post", //以Post方式發送請求
        data : 請求時發送的數據,
        dataType : json, //返回的數據類型
        async : true, //本次請求是否為異步請求
        success : function(返回的數據變量){
            //請求成功,執行的操作
        },
        error : function(){
            //請求失敗,執行的操作
        }
    });
});

$( function (){
     $.ajax({
         url : 請求的路徑(action),
         type :  "post" //以Post方式發送請求
         data : 請求時發送的數據,
         dataType : json,  //返回的數據類型
         async :  true //本次請求是否為異步請求
         success :  function (返回的數據變量){
             //請求成功,執行的操作
         },
         error :  function (){
             //請求失敗,執行的操作
         }
     });
});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM