Ahm*_*mad 6 javascript spring-mvc reactjs
我有一个用 jquery 和 spring mvc 开发的 Web 应用程序...一切都运行良好...但现在我想在我的应用程序中使用 React JS...我想在 React js 中创建一个表单并发送 ajax 请求到我的 spring mvc 控制器...我知道如何使用 jquery 执行此操作,但不知道如何使用 React js...请告诉我一种创建表单并向 spring mvc 控制器发送请求的方法...这是我的我想要获取请求的控制器方法...
@RequestMapping(value = "/saveuser", method = RequestMethod.POST)
public @ResponseBody String Save(/*@Valid Users user, BindingResult result,*/HttpServletRequest request, Model model,
@RequestParam(required = false) Boolean reverseBeforeSave) {
String userName = request.getParameter("username");
String password = request.getParameter("password");
String firstName = request.getParameter("first_name");
String lastName = request.getParameter("last_name");
System.out.println("save method");
String[] roleNames = request.getParameterValues("roles");
userService.saveUserandRoles(userName, password, firstName, lastName, roleNames);
return "success";
}
Run Code Online (Sandbox Code Playgroud)
我在 StackOverflow 中浏览了不同的解决方案,并在谷歌上进行了搜索,但没有得到任何正确的结果。
安装axios
$ npm install axios
Run Code Online (Sandbox Code Playgroud)
导入axios
import axios from 'axios';
Run Code Online (Sandbox Code Playgroud)
示例 GET 请求
axios.get('https://api.example.com/')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Run Code Online (Sandbox Code Playgroud)
POST 请求示例
var body = {
firstName: 'testName',
lastName: 'testLastName'
};
axios.post('https://api.example.com/', body)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Run Code Online (Sandbox Code Playgroud)
您需要从您的react.js应用程序发送XMLHttp请求到服务器。例子:
var http = new XMLHttpRequest();
var url = "http://<server-url>/saveuser";
var params = "param1=param1Value¶m2=param2Value";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
Run Code Online (Sandbox Code Playgroud)
您还可以使用一些漂亮的库,例如axios、fetch、superagent、request等。
| 归档时间: |
|
| 查看次数: |
23294 次 |
| 最近记录: |