現代 Web 開發建議使用 AJAX 非同步傳值,而非舊式 location.href 跳轉。
function updateData() {
var param = {
id: $('#itemId').val(),
name: $('#itemName').val(),
value: $('#itemValue').val()
};
$.ajax({
url: '/api/update',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(param),
success: function(resp) {
alert('更新成功');
}
});
}
@RestController
@RequestMapping("/api")
public class DataController {
@Autowired
private DataService dataService;
@PostMapping("/update")
public ResponseEntity<String> update(@RequestBody UpdateRequest request) {
try {
dataService.update(request.getId(), request.getName(), request.getValue());
return ResponseEntity.ok("success");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("更新失敗: " + e.getMessage());
}
}
// 內部 DTO
static class UpdateRequest {
private Long id;
private String name;
private String value;
// getter/setter 省略
}
}
@Service
@Transactional
public class DataService {
@Autowired
private DataRepository repository;
public void update(Long id, String name, String value) {
DataEntity entity = repository.findById(id)
.orElseThrow(() -> new EntityNotFoundException("資料不存在"));
entity.setName(name);
entity.setValue(value);
repository.save(entity);
}
}
@RequestBody 綁定 JSON 參數,避免手動解析。@Transactional 保證一致性。