I have a userscript that fires an ajax call via GM_xmlhttprequest to load a simple page with some text and links into a div named "debug". this works very well. now I want, that every link in the requested document is requested via gm_xmlhttprequest. I don't know why my function is not working
$('.ajax, .ajaxn').click(function(event) {
event.preventDefault();
var href = $(this).attr('href');
GM_xmlhttpRequest({
method: "GET",
url: href,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function(response) {
$('#debug').html('');
$('#debug').append(response.responseText).fadeIn(5000);
}
});
});
The links inside the response have the class ajaxn, and the firebug dom/html panel shows that the response is actually inserted into the #debug
any hints?
The question is not clear, but assuming you want that click
handler to fire, if a link is clicked in the #debug
content (versus auto-loading the links or ???)...
Then don't use the .click()
method. Use jQuery's .on()
method this fires on current, and any future, nodes that match the selector.
The code becomes something like:
$(document).on ("click", ".ajax, .ajaxn", function (event) {
event.preventDefault ();
var href = $(this).attr('href');
GM_xmlhttpRequest ( {
method: "GET",
url: href,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function (response) {
$('#debug').empty ();
$('#debug').append (response.responseText).fadeIn (5000);
}
} );
} );
Also, don't use $('#debug').html('');
Use $('#debug').empty();
instead. This will be a smidge faster and the code is a little more self-documenting.