后来通常用于通信的 API 之一是 fetch,它也在慢慢成为浏览器标准。
fetchAPI文档
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
fetch用法
更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('http://example.com/movies.json', { // optional fetch options
body: JSON.stringify(data), // you may send any data, encoded as you wish. shall match content-type
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // *manual, follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(function(response) {
// manipulate response object
// check status @ response.status etc.
return response.json(); // parses json
})
.then(function(myJson) {
// use parseed result
console.log(myJson);
});
跨浏览器兼容性
由于浏览器并不总是统一的,您可以考虑使用 polyfill,例如 whatwg-fetch @ https://github.com/github/fetch
Form 与 fetch 反应
import React from 'react';
export class ReactForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
first_name: '',
last_name: '',
};
}
onSubmit(e) {
e.preventDefault();
fetch('http://example.com/movies.json', {
body: JSON.stringify(this.state),
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'content-type': 'application/json'
},
method: 'POST',
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer',
})
.then(function (response) {
console.log(response);
if (response.status === 200) {
alert('Saved');
} else {
alert('Issues saving');
}
// you cannot parse your "success" response, since that is not a valid JSON
// consider using valid JSON req/resp pairs.
// return response.json();
});
}
render() {
return (
<form onSubmit={this.onSubmit.bind()}>
<input type="text" name="username" onChange={e => this.setState({username: e.target.value})}/>
<input type="password" name="password" onChange={e => this.setState({password: e.target.value})}/>
<input type="text" name="first_name" onChange={e => this.setState({first_name: e.target.value})}/>
<input type="text" name="last_name" onChange={e => this.setState({last_name: e.target.value})}/>
<button type="submit">Submit</button>
</form>
);
}
}