ajax call restful interface

HTTP verb Corresponding operation
POST new information
GET getting information
PUT Update information
DELETE delete message

 


1. POST-----new information
1. Background interface

@PostMapping(value = "/save")
public String save(@RequestBody(required = true) Emp emp){
    System.err.println(emp.toString());
    // 将数据信息存库
    empService.saveEmp(emp);
    return "Object Save to DB!!!";
}


Using the @PostMapping annotation means that the interface must be requested in POST mode;

Using the @RequestBody annotation means that the input parameters when requesting the interface must be data in JSON format;

2. ajax request

        let parms = {"id": "1001","name":"爱吃红豆的猫"};
        $.ajax({
            url:'/save',
            data: JSON.stringify(parms),
            type:'POST',
            dataType:'text',// 返回数据类型,因为后台返回的不是json格式的数据,所以如果这里使用json,则前台控制台打印的会是2,而不是1;
            contentType:"application/json;charset=UTF-8",
            success:function(data) {
                console.log(1)
            },
            error:function(data) {
                console.log(2)
            }
        })


Since the background interface uses the @PostMapping annotation, the type attribute in ajax must be POST;

Since the background interface uses the @RequestBody annotation, the ajax data must be in json format, so you need to use JSON.stringify() to convert the data into a json format string;

At the same time, you need to specify the contentType as "application/json;charset=UTF-8", because the default is 'application/x-www-form-urlencoded;charset=UTF-8';

2. GET-----get information
1. Background interface

@GetMapping(value = "/restful/{id}/{orderindex}")
public String info(@PathVariable(required = true) String id, @PathVariable(required = true) long orderindex){
    BoTaskPlan boTaskPlan = new BoTaskPlan();
    boTaskPlan.setId(id);
    boTaskPlan.setOrderindex(orderindex);
    BoTaskPlan bo = this.service.getOne(boTaskPlan);
    return bo.toString();
}


Using the @GetMapping annotation means that the interface must be requested in GET mode;

Using the @PathVariable annotation means that the input parameter when requesting the interface is on the URI (URI is the part of the URL except http and domain name or IP port);

2. ajax request

        let id = "1001";
        let orderindex = "7";
        $.ajax({
            url:'/restful/' + id + "/" + orderindex,
            type:'GET',
            dataType:'json',
            contentType:"application/json;charset=UTF-8",
            success:function(data) {
                console.log(1)
            },
            error:function(data) {
                console.log(2)
            }
        })



Since the background interface uses the @GetMapping annotation, the type attribute in ajax must be GET;

Since the @PathVariable annotation is used in the background, the parameters are directly placed after the "/" of the URL instead of after? as before;

3. PUT-----update information
1. Background code

@PutMapping(value = "/restful")
public String update(@RequestBody(required = true) BoTaskPlan bo){   // 使用@PathVariable获取{XXX}中的XXX变量值
    // 更新数据
    service.updateById(bo);
    // 查询数据
    bo = service.getOne(bo.getId());
    return bo.toString();
}


Using the @PutMapping annotation means that the interface must be requested using the PUT method;

Since the background interface uses the @RequestBody annotation, the ajax data must be in json format, so you need to use JSON.stringify() to convert the data into a json format string;

2. ajax request

        let arr = {"createuser":"admin","id":"1002"};
        $.ajax({
            url:'/restful',
            data: JSON.stringify(arr),
            type:'PUT',
            dataType:'json',    
            contentType:"application/json;charset=UTF-8",
            success:function(data) {
                console.log(1)
            },
            error:function(data) {
                console.log(2)
            }
        })


Since the background interface uses the @PutMapping annotation, the type attribute in ajax must be PUT;

Since @RequestBody is used in the background, the data of ajax must be a json string

4. DELETE-----delete information
1. background code

@DeleteMapping(value = "/restful/{id}")
public String delete(@PathVariable(required = true) String id){   // 使用@PathVariable获取{XXX}中的XXX变量值
    // 删除信息
    service.deleteById(id);
    // 查询所有信息
    List<BoTaskPlan> list = service.getAll();
    return list.toString();
}


Using the @DeleteMapping annotation means that the interface must be requested in DELETE mode;

Using the @PathVariable annotation means that the input parameter when requesting the interface is on the URI (URI is the part of the URL except http and domain name or IP port);

2. ajax request

        $.ajax({
            url:'/restful/22311',
            type:'DELETE',
            dataType:'json',    
            contentType:"application/json;charset=UTF-8",
            success:function(data) {
                console.log(1)
            },
            error:function(data) {
                console.log(2)
            }
        })


Since the background interface uses the @DeleteMapping annotation, the type attribute in ajax must be DELETE;

Since the @PathVariable annotation is used in the background, the parameters are directly placed after the "/" of the URL instead of after? as before;

AJAX calls RESTFUL interface across domains

1. JSONP method
front-end code:

let patientInfoURL = 'http://10.1.8.82:8332/soap/GetPatInfo?citycardno=0000997144446894&id=32010600000002012';
$.ajax({
     type:'get',
     url: patientInfoURL ,
     dataType:'jsonp',
     //jsonp:'callback',//默认就是callback,可以不写
     //jsonpCallback:"successCallback",//此处定义请求url中callback参数后的值,不写则jQuery会自动生成一个字符串
     success:function(data){
        console.log(data);
     },
     error:function(XMLHttpRequest, textStatus, errorThrown){
          alert(XMLHttpRequest.status);
          alert(XMLHttpRequest.readyState);
          alert(textStatus);
     }
 });

For Ajax cross-domain requests, the browser will automatically add two params after the requested url, one key=callback and the other key=_. The value callback of the first key can be changed through jsonp:'callback', and the default is callback. The purpose of the second key is unclear and does not affect the use

  • Customize the callback name of jsonp (ie with jsonpCallback: "successCallback")

  • The callback name of jsonp is not customized (that is, without jsonpCallback: "successCallback") 

 code behind

Response.ContentType="text/html; charset=utf-8";
String callback = Request.QueryString["callback"].ToString();
Response.Write(callback + "{ \"success\": [{ \"id\": 1, \"title\": \"title 1\" }, { \"id\": 2, \"title\": \"title 2\" }, { \"id\": 3, \"title\": \"title 3\"}] }");

Get the callback function name by getting the key of the param in the front-end request url as the value of callback. 

2. CORS method
Introduction:

CROS is currently the mainstream solution to cross-domain problems, and it is estimated to be a trend in the future.

Cross-Origin Resource Sharing  (CORS) is a W3c working draft that defines how browsers and servers communicate when accessing resources across domains. The basic idea behind CORS is to use custom HTTP headers to allow the browser and server to understand each other and thus determine whether a request or response was successful or not.

The Ajax cross-domain request in the CORS method looks the same as the normal non-cross-domain Ajax request, and it is true. This is also a bit of the CORS method. The work done is no different from non-cross-domain, the main difference is in the back-end code.

Background code: 

// 跨域配置
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Max-Age", "3600"); // 保持跨域Ajax时的Cookie
response.setHeader("Access-Control-Allow-Headers", "x-auth-token, x-requested-with,Authorization,Origin, Accept, Content-Type,x-xsrf-token");

Guess you like

Origin blog.csdn.net/weixin_42693104/article/details/129281230