SpringMVC通過(guò)Ajax處理JSON數(shù)據(jù)

下面舉一個(gè)簡(jiǎn)單的例子,提供部分代碼:
1.導(dǎo)入jar包(注意版本一致)。
jackson-annotations.jar
jackson-core.jar
jackson-databind.jar

2.前端:服務(wù)端將返回值結(jié)果 以json數(shù)組的形式 傳給了result。
部分代碼:

    $("#testJson").click(function(){
                    //通過(guò)ajax請(qǐng)求springmvc
                    $.post(
                        "handler/testJson",//服務(wù)器地址
                        //例如{"name":"zs","age":23}這樣的json數(shù)據(jù)
                        function(result){//服務(wù)端處理完畢后的回調(diào)函數(shù) List<Student> students, 加上@ResponseBody后, students實(shí)質(zhì)是一個(gè)json數(shù)組的格式
                            for(var i=0;i<result.length ;i++){
                                alert(result[i].id +"-"+result[i].name +"-"+result[i].age);
                            }
                        }
                    );

3.控制器
@ResponseBody修飾方法,會(huì)將該方法的返回值 以一個(gè)json數(shù)組的形式返回給前端。
部分代碼:

@ResponseBody//告訴SpringMVC,此時(shí)的返回 不是一個(gè) View頁(yè)面,而是一個(gè) ajax調(diào)用的返回值(Json數(shù)組)
        @RequestMapping(value="testJson")
        public List<Student> testJson() {
            //Controller-Service-dao
            //StudentService studentService = new StudentServiceImp();
           //List<Student> students =  studentService.qeuryAllStudent();
           //模擬調(diào)用service的查詢操作
            ...
            List<Student> students = new ArrayList<>();
            students.add(stu1) ;
            students.add(stu2) ;
            students.add(stu3) ;
            
            return students;
        }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容