jQuery ajax 简单的实例

通过jQuery ajax实现从服务器查询数据,返回给前端并显示到html页面

html文件




    
    使用 jQuery validate 表单验证
    
    
    
    






login.js文件



function findAllDepts() {
    $.ajax({
        async : false,    //表示请求是否异步处理
        type : "post",    //请求类型
        url : "/getDepts",//请求的 URL地址
        dataType : "json",//返回的数据类型
        success: function (data) {
          console.log(data);  //在控制台打印服务器端返回的数据
          for(var i=0;i——请选择——');
            for(var i=0;i';
                html +=data[i].deptName + '';
                $("select[name='departmentId']").append(html);  //将数据显示在html页面
            }
        },
        error:function (data) {
            alert(data.result);
        }
    });
};

$(document).ready(function () {
   findAllDepts();  //页面加载完成就执行该方法
});

后端对应的请求方法(项目为springboot项目)

package com.njxz.demo.controller;

import com.njxz.demo.domain.Department;
import com.njxz.demo.domain.User;
import com.njxz.demo.service.IUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class UserController {

    @Resource
    private IUserService userService;
  

    @RequestMapping("/getDepts")
    public List getDepts(){ //查找所有部门
        List depts=userService.findAllDepts();
        return depts;
    }
}

后端返回的对象类

package com.njxz.demo.domain;

public class Department {
    private Integer deptId;

    private String deptName;

    public Integer getDeptId() {
        return deptId;
    }

    public void setDeptId(Integer deptId) {
        this.deptId = deptId;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName == null ? null : deptName.trim();
    }
}

控制台打印的数据信息

jQuery ajax 简单的实例_第1张图片

 

html页面显示效果

jQuery ajax 简单的实例_第2张图片

你可能感兴趣的:(jquery)