jquery ajax getJson()


jquery ajax getJson()

 

应用:从json文件,或者从后端服务器中获取json数据

 

 

*********************

语法:getJson(url,[data],[callback])

 

url:加载json数据的地址

data:可选,传递给后端服务的数据

 

callback:可选,请求成功后调用,回调参数:

data:响应数据

status:请求状态

xmlhttpRequest:http请求对象

 

 

*********************

示例:加载json文件

 

                               jquery ajax getJson()_第1张图片

 

test.json

{
  "username": "瓜田李下",
  "age": 20
}

 

index.html




    
    Title
    



 

 

点击按钮

                               

 

 

*********************

示例:后端服务器加载json数据

 

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello 瓜田李下";
    }

    @RequestMapping("/hello2")
    public String hello2(String name){
        return "hello "+name;
    }

    @RequestMapping("/hello3")
    public Map hello3(String name){
        Map map=new HashMap<>();
        map.put("info",name);

        return map;
    }
}

返回的数据类型为map json格式会解析,返回string不会解析

 

index.html




    
    Title
    



 

 

点击按钮

                               

 

 

*********************

示例:后端加载 json 数据(跨域)

 

helloController(端口号:8081

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public void hello(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Map map=new HashMap<>();
        map.put("name",request.getParameter("name"));
        map.put("age",20);

        String callbackName=request.getParameter("jsonCallback");
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(callbackName+"("+ JSON.toJSONString(map)+")");
    }
}

jsonCallback:回调参数参数名callbackname:随机生成的函数名

 

 

index.html(端口号:8080)




    
    Title
    



 

 

点击按钮

                               

 

 

你可能感兴趣的:(jquery)