كيف يمكنني إرجاع قيمة من gm_xmlhttprequest؟
-
22-08-2019 - |
سؤال
لدي هذا الرمز هنا:
var infiltrationResult;
while(thisOption) {
var trNode = document.createElement('tr');
var tdNode = document.createElement('td');
var hrefNode = document.createElement('a');
infPlanetID = thisOption.getAttribute('value');
var myURL = "http://www.hyperiums.com/servlet/Planetinf?securitylevel=90&newinfiltr=New+infiltration&planetid=" + PlanetID + "&infplanetid=" + infPlanetID;
GM_xmlhttpRequest({
method: 'GET',
url: myURL,
headers: {
'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
'Accept': 'application/atom+xml,application/xml,text/xml',
},
onload: function(responseDetails) {
if (responseDetails.responseText.match(/<b>Invalid order<\/td><\/tr><tr><td><BR><center><font color=#AAAA77 face=verdana,arial size=2>The target planet is blocking all infiltrations[\s\S]<BR><BR>/im)) {
// Successful match
infiltrationResult = 'Invalid Order';
} else {
// Match attempt failed
infiltrationResult = 'Infiltration Successfully Created';
}
}
});
عندما أضيف
في حالة تأهب (تسرب الترشيح) ؛
مباشرة بعد تعيينه ، أرى السلسلة بشكل صحيح.
ومع ذلك ، بعد خروج الوظيفة ، جربت نفس التنبيه وأحصل على:
undefined
أي أفكار ما أفعله خطأ؟
المحلول
يعمل الطلب بشكل غير متزامن. هذا لماذا الوظيفة تأخذ onload
وظيفة رد الاتصال في المقام الأول. إذا كانت متزامنة ، إذن GM_xmlhttpRequest
سيؤدي ببساطة إلى إرجاع تفاصيل الاستجابة مثل وظيفة عادية.
أثناء انتظار عودة الطلب ، الرمز بعد المكالمة إلى GM_xmlhttpRequest
يواصل الجري. يحدد البرنامج النصي الخاص بك ذلك بشكل صحيح infiltrationResult
غير محدد لأن الطلب لم يكتمل بعد.
إذا كنت بحاجة إلى القيام بأكثر من مجرد تعيين المتغير عندما يعود الطلب ، فقم بذلك في onload
أتصل مرة أخرى.
نصائح أخرى
جرب هذا:
var infiltrationResult;
while(thisOption) {
var trNode = document.createElement('tr');
var tdNode = document.createElement('td');
var hrefNode = document.createElement('a');
infPlanetID = thisOption.getAttribute('value');
var myURL = "http://www.hyperiums.com/servlet/Planetinf?securitylevel=90&newinfiltr=New+infiltration&planetid=" + PlanetID + "&infplanetid=" + infPlanetID;
GM_xmlhttpRequest({
method: 'GET',
url: myURL,
headers: {
'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
'Accept': 'application/atom+xml,application/xml,text/xml',
},
onload: function(responseDetails) {
if (responseDetails.responseText.match(/<b>Invalid order<\/td><\/tr><tr><td><BR><center><font color=#AAAA77 face=verdana,arial size=2>The target planet is blocking all infiltrations[\s\S]<BR><BR>/im)) {
// Successful match
infiltrationResult = 'Invalid Order';
} else {
// Match attempt failed
infiltrationResult = 'Infiltration Successfully Created';
}
sentback(infiltrationResult);//Sent it when it loads only
}
});
function sentback(x){
alert(x);
}
لا تنتمي إلى StackOverflow