[英]PageMethods in javascript as return of a function
javascript:
var Enabled = false;
function GateWay_Enabled(GateWay_Name) {
PageMethods.GateWay_Enabled(GateWay_Name, onRequestComplete, onError);
return Enabled;
}
function onRequestComplete(result) {
Enabled = result;
}
function onError(result) {
alert('Error');
}
var MyVariable = GateWay_Enabled('GateWay_Name');
服務器端代碼(C#):
[WebMethod]
[ScriptMethod]
public static bool GateWay_Enabled(string GateWay_Name)
{
bool Enabled = true;
return Enabled;
}
為什么MyVariable始終為假?
還有另一種寫PageMethods.GateWay_Enabled(GateWay_Name, onRequestComplete, onError);
作為GateWay_Enabled
函數的返回? 我正在尋找這樣的東西:
var MyBoolVariable =
bool.parse(PageMethods.GateWay_Enabled(GateWay_Name,
onRequestComplete, onError));
編輯1:
一切正常,PageMethods沒有錯誤。
腳本管理器中的EnablePageMethods為true。
編輯2:
我無法將MyVariable放在onRequestComplete()函數中。
我使MyVariable可以簡化我的代碼。
MyVariable的真實代碼是:
GateWays = [
{ "Cod": 1, "Enabled": GateWay_Enabled('1') },
{ "Cod": 2, "Enabled": GateWay_Enabled('2') },
{ "Cod": 3, "Enabled": GateWay_Enabled('3') },
{ "Cod": 4, "Enabled": GateWay_Enabled('4') },
{ "Cod": 5, "Enabled": GateWay_Enabled('5') },
{ "Cod": 6, "Enabled": GateWay_Enabled('6') },
{ "Cod": 7, "Enabled": GateWay_Enabled('7') }
];
我想在另一個地方使用此數組。
我不能將其放在onRequestComplete()函數中。
我該怎么辦?
您需要重構代碼。 現在,您正在使用GateWay_Enabled
方法執行結果之后。 將這些東西放在單獨的方法中,然后從onRequestComplete
方法中調用它;
var Enabled = false;
function GateWay_Enabled(GateWay_Name) {
PageMethods.GateWay_Enabled(GateWay_Name, onRequestComplete, onError);
}
function onRequestComplete(result) {
alert(result); // you will get results here;
Enabled = result;
//do something with value
}
function onError(result) {
alert('Error');
}
GateWay_Enabled('GateWay_Name'); // you can't get direct output from this method,
// have to get results from success callback method or onError callback method
調用PageMethods是異步的:在調用onRequestComplete
函數之前,將執行return Enabled
行return Enabled
。
嘗試將任何讀取MyVariable
代碼放入onRequestComplete
函數中,而使用result
代替。
在您進行Edit2和評論后,我建議您:
GateWays
數組,以避免進行7個AJAX調用。 onRequestComplete
方法中。 另外,如果這些數據在用戶點擊之間沒有變化,建議您在服務器端獲取。
沒有簡單的方法來確保用戶單擊代碼一直等到所有七個呼叫都完成之后。
您是否在ScriptManager中添加了EnablePageMethods =“ true”?
您正在執行onRequestComplete
之前檢查MyVariable
的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.