How Can I Handle Multiple Ajax Results In A Userscript?
I'm currently developing a Greasemonkey script to translate
Solution 1:
Update: With newer versions of Greasemonkey and Tampermonkey, you can now pass a context
:
GM_xmlhttpRequest ( {
method: 'GET',
url: fullurl,
context: i,
headers: {
'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey',
'Accept': 'application/atom+xml,application/xml,text/xml',
},
onload: function (responseDetails) {
var destination = "{" + responseDetails.context + "}"; // context is `i`if (responseDetails.status == 200) {
var data = $.parseJSON (responseDetails.responseText);
translated_text[i] = data.responseData.translatedText.replace (/"/g,"\"")
.replace (/'/g,"\"").replace (/>/g,">")
;
textarea.text (textarea.text ().replace ("{"+i+"}",translated_text[i]) );
}
else {
alert (
'Request Failed : '+responseDetails.status+"\nError : "
+ responseDetails.statusText
);
}
}
} );
For other/older platforms, to use the value of i
, you need to wrap it in a JavaScript closure. One way to do do that is:
( function (i) {
GM_xmlhttpRequest ( {
method: 'GET',
url: fullurl,
headers: {
'User-agent': 'Mozilla/5.0 (compatible) Greasemonkey',
'Accept': 'application/atom+xml,application/xml,text/xml',
},
onload: function (responseDetails) {
var destination = "{"+i+"}";
if (responseDetails.status == 200) {
var data = $.parseJSON (responseDetails.responseText);
translated_text[i] = data.responseData.translatedText.replace (/"/g,"\"")
.replace (/'/g,"\"").replace (/>/g,">")
;
textarea.text (textarea.text ().replace ("{"+i+"}",translated_text[i]) );
}
else {
alert (
'Request Failed : '+responseDetails.status+"\nError : "
+ responseDetails.statusText
);
}
}
} );
} ) (i);
Solution 2:
As far as I understand it you can use jQuery to do cross domain requests like this...
functionpass_ajax(url,text_to_translate){
$.ajax({
type: 'GET',
url: url,
crossDomain: true,
data: text_to_translate,
dataType: 'json',
success: function(data){
req = data; //here you can sanitize the data before concatenating
},
complete: function(xhr,textStatus){
translated_text += req;
}
});
The 'crossDomain: true' property is new to jQuery 1.5. Also, I think you could make use of success and complete and just concatenate the text as it returns, assigning it to a variable with outer scope.
Post a Comment for "How Can I Handle Multiple Ajax Results In A Userscript?"