今天使用promise+ajax+php来查询数据库中用户名
js代码:
function ajax(opts) {
opts = Object.assign({
type: 'GET',
data: ''
}, opts);
var promise = new Promise((resolve,reject)=>{
let xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status == 200) {
resolve(xhr.responseText);
}
else {
reject(xhr.statusText);
}
};
if (typeof opts.data == 'object') {
let tmp = [];
for (var attr in opts.data) {
tmp.push(attr + '=' + opts.data[attr]);
}
opts.data = tmp.join('&');
}
if (opts.type == 'GET') {
xhr.open('GET', `${opts.url}?${opts.data}`, true);
xhr.send(null);
}
else if (opts.type == 'POST') {
xhr.open('POST', `${opts.url}`, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(opts.data);
}
});
return promise;
}
var j = ajax({
url: '2_ajax_server.php',
data : {username : 'xiaoming' , age : 20}
});
j.then(function(res){
console.log(res);
}).catch(function(err){
console.log(err);
});
php代码:
$username = isset($_REQUEST['username']) ? $_REQUEST['username'] : '';
echo $username;
小白一名,如有错误欢迎指出