[英]What is the right way to use “context:…” in an AJAX call?
因此,我知道關於AJAX和上下文的使用有很多線程,但是經過數小時的閱讀和嘗試后,我打開了一個新線程。
所以我有這個(縮短版本)的JavaScript功能:
this.CallService = function () {
var Type = this.Type;
var Url = this.Url;
var Data = this.Data;
var ContentType = this.ContentType;
var DataType = this.DataType;
var ProcessData = this.ProcessData;
var ClipUrl = this.ClipUrl;
var CountMax = this.CountMax;
var Callback = this.Callback;
var SucceededServiceCallback = this.SucceededServiceCallback;
var FailedServiceCallback = this.FailedServiceCallback;
return $.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
context: this,
}).done(function (msg) {//On Successfull service call
SucceededServiceCallback(this, msg);
}).fail(function (msg) {
FailedServiceCallback(this, msg);
});
}
這里的重點是context: this
和兩個回調done
和fail
。 在這兩個回調中,我this
上下文賦予我的回調函數:
this.SucceededServiceCallback = function (context, result) {
if (null != context) {
UpdateDebugInfo(context, "succeeded: " + context.DataType + " URL: " + context.Url + " Data: " + context.Data + " Result: " +result);
}
if (context != null && context.DataType == "json" && result != null && context.Callback != null) {
context.Callback(context, result);
}
}
這里重要的部分是我使用上下文查看訪問變量DataType,Callback,Url等。
現在的問題是,上下文被設置為最后使用的上下文(這是一個異步調用,因此所有變量都是上次調用中的變量)。 因此,我很確定該context: this,
部分。 我只是不知道如何使用這項權利。 謝謝你的幫助。
tl; dr:
我使用context: this
在Ajax調用中。 上下文始終設置為最后一個“ this”調用。 我想使用呼叫的“ this”。
在觸發每個請求之前,您正在“緩存”所有變量,但是在SucceededServiceCallback
函數中,您正在檢查this.XXX
這不是您期望的var Type
,而是實際的this.Type
本身。
您可以做的就是將這些屬性放到一個對象中,並將其作為上下文(而不是主對象)傳遞:
this.CallService = function () {
var context = {
Type : this.Type,
Url : this.Url,
Data : this.Data,
ContentType : this.ContentType,
DataType : this.DataType,
ProcessData : this.ProcessData,
ClipUrl : this.ClipUrl,
CountMax : this.CountMax,
Callback : this.Callback
};
var SucceededServiceCallback = this.SucceededServiceCallback;
var FailedServiceCallback = this.FailedServiceCallback;
return $.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
context: context,
}).done(function (msg) {//On Successfull service call
SucceededServiceCallback(this, msg);
}).fail(function (msg) {
FailedServiceCallback(this, msg);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.