[英]Recreating jQuery's $.ajax().done()
我正在嘗試創建自己的“基本” javascript框架,希望它以與jQuery
相似的方式工作,並且我愛上了方法鏈接而不是回調。 但是,對我來說,作為初級javascripter來說,實現這一點很困難。
現在,我已經創建了自己的ajax
“類”,但似乎無法弄清楚如何重新創建jQuery使用的.done()
。
我希望此語法能夠起作用,以擺脫回調地獄;
ajax(url, type, data).success(function(response){});
但是,這導致response
為false
。 顯然,因為它是在我的ajax調用完成之前就被調用的。
我嘗試插入一個promise,但這只會讓我出現很多語法錯誤或模糊的錯誤,例如uncaught (in promise) OK
。
這就是我的代碼當前的樣子;
var ajax = function(url, method, data) {
if(!(this instanceof ajax))
{
return new ajax(url, method, data);
}
var ajaxObj = this;
var prom = new Promise(function(resolve, reject) {
ajaxObj.xhttp = new XMLHttpRequest();
ajaxObj.url = url;
ajaxObj.data = data;
ajaxObj.urlParams = '';
ajaxObj.response = false;
ajaxObj.get();
ajaxObj.xhttp.send();
ajaxObj.xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200)
{
resolve(this.responseText);
}
else
{
reject(this.statusText);
}
};
});
return prom;
};
ajax.prototype.get = function() {
var urlParams = serialize(this.data);
this.xhttp.open("GET", this.url + urlParams);
return this;
};
ajax.prototype.success = function(callBack) {
callBack(this.response);
};
//My function call;
ajax('url', 'GET', {
'Testval': 'testvalue',
'field': 'value'
}).then(function(response) {
console.log("Response is:" + response);
}).catch(function(response){});
-對於那些想知道的人,我的序列化功能是:
var serialize = function(obj, prefix) {
var str = [], p;
for(p in obj)
{
if(obj.hasOwnProperty(p))
{
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return '?' + str.join("&");
};
- 注意:
我希望能夠像這樣調用我的ajax函數:
ajax(url, type, data).success(function(response){
//The responseData has already been handled by the success function before the callback.
//On success
}).error(function(error){
// On error
});
-這並不一定是通過承諾。 可以通過任何可能的方式,我只是一無所知。
這就是您兌現承諾的方式。 在這種情況下, ajax
將返回該諾言,因此將不是構造函數。 then
調用鏈接方法。
var ajax = function(url, method, data) { return new Promise(function (resolve, reject) { var xhttp = new XMLHttpRequest(), strType = method.toLowerCase(), methods = { get: function() { var urlParams = serialize(data); xhttp.open("GET", url + urlParams); } }; methods[strType](); xhttp.send(); xhttp.onreadystatechange = function() { if (this.readyState !== 4) return; resolve(this.status == 200 ? this.responseText : this.statusText); }; xhttp.onerror = xhttp.onabort = reject; }); }; //My function call; ajax('http://httpstat.us/200?sleep=200', 'GET', { 'Testval': 'testvalue', 'field': 'value' }).then(function(response) { console.log("Response is:" + response); }).catch(function() { console.log("There was an error or the request was aborted."); }); function serialize(obj, prefix) { var str = [], p; for(p in obj) { if(obj.hasOwnProperty(p)) { var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p]; str.push((v !== null && typeof v === "object") ? serialize(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v)); } } return '?' + str.join("&"); };
如果您更喜歡success
的名稱,請執行以下操作:
var promise = new Promise(function (resolve, reject) {
// ...etc
});
promise.success = promise.then;
promise.error = promise.catch;
return promise;
:-)當然,現在您有了一個帶有非標准方法名稱的Promise對象,這並不是真正的最佳實踐。 更好地遵守標准承諾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.