Wie kann ich einen Wert von gm_xmlhttprequest zurückgeben?
-
22-08-2019 - |
Frage
Ich habe diesen Code hier:
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';
}
}
});
Wenn ich hinzufüge
Alarm (InfiltrationResult);
Gleich nachdem es zugewiesen wurde, sehe ich die Zeichenfolge richtig.
Nachdem die Funktion beendet ist, habe ich den gleichen Alarm ausprobiert und bekomme:
undefined
Irgendwelche Ideen, was ich falsch mache?
Lösung
Die Anfrage läuft asynchron. Das ist warum Die Funktion nimmt eine onload
Rückruffunktion in erster Linie. Wenn es synchron war, dann GM_xmlhttpRequest
Würde einfach die Antwortdetails wie eine gewöhnliche Funktion zurückgeben.
Während der Wartezeit auf die Rückgabe der Anfrage den Code nach dem Anruf an GM_xmlhttpRequest
Läuft weiter. Ihr Skript identifiziert das richtig infiltrationResult
ist undefiniert, weil die Anfrage noch nicht abgeschlossen wurde.
Wenn Sie mehr als nur die Variable zuweisen müssen, wenn die Anforderung zurückkommt, dann tun Sie dies in der onload
zurückrufen.
Andere Tipps
Versuche dies:
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);
}