【Java】数据交换 Json 和 异步请求 Ajax
    		       		warning:
    		            这篇文章距离上次修改已过439天,其中的内容可能已经有所变动。
    		        
        		                
                在Java后端处理数据交换,可以使用Jackson库来处理JSON数据,并使用Spring框架的@RestController和@RequestMapping注解来创建RESTful API。对于异步请求,可以使用JavaScript的XMLHttpRequest或现代的fetch API来发送Ajax请求。
以下是一个简单的例子:
Java后端(Spring Boot):
import org.springframework.web.bind.annotation.*;
 
@RestController
public class DataController {
 
    @GetMapping("/data")
    public MyData getData() {
        // 模拟数据
        MyData data = new MyData();
        data.setId(1);
        data.setName("Sample");
        return data;
    }
 
    @PostMapping("/data")
    public void updateData(@RequestBody MyData newData) {
        // 更新数据逻辑
    }
 
    static class MyData {
        private int id;
        private String name;
 
        // getters and setters
    }
}JavaScript前端(使用fetch API):
// 获取数据
fetch('/data')
  .then(response => response.json())
  .then(data => {
    console.log('Received data:', data);
  });
 
// 发送数据
var data = { id: 1, name: 'Sample' };
fetch('/data', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then(response => response.text())
.then(response => console.log(response));在这个例子中,Java后端定义了两个简单的RESTful API,用于获取(GET)和更新(POST)数据。JavaScript前端使用fetch API来异步发送请求,并处理响应。
评论已关闭