1、封装jQuery的ajax方法
var btn = document.querySelector( 'button' );
btn.onclick = function () {
$.ajax( {
type: 'post',
url: '...',
data: { name: 'itcast', age: 10 },// 要在ajax工具函数中把对象转换成key=value&key=value的形式
success: function ( data ) {
console.log( data );
}
})
}
var $ = {
// 处理对象的方法
param: function ( obj ) {
var httpStr = '';
for ( var k in obj ) {
httpStr += k + '=' + obj[ k ] + '&';
}
httpStr = httpStr.slice( 0, -1 );
return httpStr;
},
ajax: function ( options ) {
// 1.请求方式
var type = options.type || 'get';
// 2.请求地址
var url = options.url || '';
// 3.请求正文--格式化数据
var data = this.param( options.data || {});
// 4.成功时的回调函数
var success = options.success;
// 1.实例化对象
var xhr = new XMLHttpRequest();
// 2.设置请求行
if ( type == "get" ) {
url = url + '?' + data;
data = null;
}
xhr.open( type, url );
// 3.设置请求头
if ( type == "post" ) {
xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
}
// 4.监听并处理相应
xhr.onreadystatechange = function () {
if ( xhr.readyState == 4 && xhr.status == 200 ) {
// 6.成功时的回调
success( xhr.responseText );
}
}
// 5.设置请求正文
xhr.send( data );
}
}
2、jQuery方法
$( 'input' ).on( 'click', function () {
$.ajax( {
type: 'post',
url: 'url',
data: null,
dataType: 'html',
beforeSend: function () {
console.log( '请求发起前' );
},
success: function ( result ) {
var arr = JSON.parse( result );
var html = '';
for ( var i = 0; i < arr.length; i++ ) {
html +=
'<tr>' +
'<td>' + arr[ i ].name + '</td>' +
'<td>' + arr[ i ].photo + '</td>'
'</tr>';
}
$( 'table' ).html( html );
},
error: function ( error ) {
// console.log( error );
},
complete: function () {
console.log( '请求完成(无论请求成功还是失败都会触发)' )
}
})
})
jQuery的get方法:
$( 'button' ).click( function () {
$.get( 'stars.php', null, function ( data ) {
console.log( data );
})
})
jQuery的post方法:
$( 'button' ).click( function () {
$.post( 'stars.php', null, function ( data ) {
console.log( data );
var html = "";
for ( var i = 0; i < data.length; i++ ) {
html +=
'<tr>' +
'<td>' + data[ i ].name + '</td>' +
'<td>' + data[ i ].age + '</td>'
'</tr>'
}
$( 'table' ).html( html );
})
})