AJAX with jQuery?
$.ajax({url:??,type:??,data:??,success: function(){??} //callback,error:function(jqXHR,textStatus,error){??}
})
? think about what AJAX wants from human ,
AJAX asks questions :
tell Me By Which Way You Want To Do Things : —— 'GET or?POST'?,
tell Me Where The Address Is? ——?url?,
tell Me What Data You Want To Get From Or Post On The Server ?——??data ,
what Do You Want To Do With The Data After Getting Or Posting It Successfully And What If An Eerror Occur? ——?callbacks
?
AJAX with JS?
window.onload = function(){var xhttp = XMLHttpRequest();
// create an AJAX object ...一般要功能檢測IE AcitveXObject,其他 XMLHttpRequestxhttp.open("Get","uri",true);
// Set AJAX request ————how ,where, async or sync //如果是‘POST’,則必須設置首部,設置返回內容的編碼類型。 //xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;")xhttp.send();
//send AJAX request and with (data) if u are posting data to the server.xhttp.onreadystatechange=function(){
//readystate狀態一有改變的話,就執行這個匿名函數,所以會執行4次
if( xhttp.readystate== 4 && xhttp.status==200){
/*一般是檢測到readystate為4,且status 返回200時,(HTTP狀態碼 200代表處理成功OK,404找不到文件等等),再執行真正的callback處理返回的數據;*/callback(xhttp.response)
//and if it's json data ,u would have to use JSON.parse }}
}
如果需要多個AJAX 請求的話,為了避免寫出 callback hell 可以用promise 對象,和 generator.
1,promise 一般是用new 創建Promise對象,
在promise對象上用then(callback)來處理數據,// then在這里,大概就是然后的意思。
如果后面還有AJAX request的話,則可以在callback 內部 return 新的 new Promise 對象,然后對執行后返回的promise對象使用.then(callback)方法。
Promise機制 是鏈式的。
2,generator 生成器 ——— function*(yield? ??){}?
var myGenerator = function*(){var data1 = yield $.get(url1);//do sth with data1var data2 = yield $.get(url2);var data3 = yield $.get(url3)}wrapGener (myGenerator) // 把generator 傳遞給 wrapGenerfunction wrapGener ( generator ){var gener = generator(); //生成生成器 return handleGenerator(gener.next()) //調用next方法,傳遞生成的對象 Object{value:"??",done:false} 給handleGenerator。function handleGenerator(yieldedObj){ if( !yieldedObj.done){//如果生成器沒有執行完畢yieldedObj.value.then(//執行callbackfunction(data){ // callback 的參數 Object.value return handleGenerator(gener.next(data))//遞歸 返回這次的object.value 給gener,賦值給包含yield的變量。并且再次調用gener的next生成新的對象。}) } }
}
var gener = generator();
//call 一個生成器并不會立刻執行,而是準備執行,有點像new func() 的創建對象,但是并沒有new關鍵字 。
只有call了gener?.next()方法,生成器才會開始執行,但是,執行到有 yield 關鍵字 的地方會暫停,而且,會返回 yield 后面的值。
// yield 差不多就是 return for now .
如果在執行過程中,遇到 N個 yield AJAX request ,則需要調用N個.next()方法。
一般是在檢測 yield 返回的對象的done屬性不為真 ,也就是說生成器還沒有執行完畢。Object.done == false 的情況下調用下一個next方法。
yield 返回給調用者的是一個有著2個屬性的對象,Object{value:"??",done:false}
而 Object.value 里面的值就是 yield 后面的 AJAX request 了,也就是服務器返回的內容。
對?Object.value 調用.then(callback)方法,就可以使用內容了。
可以在callback function內部用遞歸的方式,再次調用 gener?.next(value) ,這個時候會返回object.value里面的值給gener,然后generator繼續執行。
?