Ajax
Posted heben
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax相关的知识,希望对你有一定的参考价值。
壹:与XMLHttpRequest绑定的,js原生的方式
示例:
<!DOCTYPE html> <html> <head> <script src="../build/react.js"></script> <script src="../build/react-dom.js"></script> <script src="../build/browser.min.js"></script> </head> <body> <div id="example" /> <script type="text/babel"> var text = "loading"; var Result = React.createClass({ getInitialState: function () { return { success:false }; }, componentDidMount: function() { var request = new XMLHttpRequest(); // 新建XMLHttpRequest对象 request.onreadystatechange = function () { // 状态发生变化时,函数被回调 if (request.readyState === 4) { // 成功完成 // 判断响应结果: if (request.status === 200) { // 成功,通过responseText拿到响应的文本: text = request.responseText; this.setState({success:true}); } else { // 失败,根据响应码判断失败原因: text = ‘failed‘; this.setState({success:false}); } } else { // HTTP请求还在继续... } }.bind(this); request.open(‘GET‘, ‘https://api.github.com/search/repositories?q=javascript&sort=stars‘); request.send(); }, render: function() { return ( <div> {text} </div> ); } }); ReactDOM.render( <Result/>, document.getElementById(‘example‘) ); </script> </body>
贰:Promise
示例:
new Promise(function (resolve, reject) { console.log(‘start new Promise...‘); var timeOut = Math.random() * 2; console.log(‘set timeout to: ‘ + timeOut + ‘ seconds.‘); setTimeout(function () { if (timeOut < 1) { console.log(‘call resolve()...‘); resolve(‘200 OK‘); } else { console.log(‘call reject()...‘); reject(‘timeout in ‘ + timeOut + ‘ seconds.‘); } }, timeOut * 1000); }).then(function (r) { console.log(‘Done: ‘ + r); }).catch(function (reason) { console.log(‘Failed: ‘ + reason); });
以上是关于Ajax的主要内容,如果未能解决你的问题,请参考以下文章