var myAjax = new Ajax.Request(
url,
{
method: 'get',
parameters: paramstring,
onSuccess: function(transport) {$('myhtmlelement').innerHTML=transport.responseText;}
});
That code would find the element with name 'myhtmlelement' and set its contents to the page returned by url. That's great, but what if you want to pass in some values from wherever you are creating the Ajax Request?
For example, I created a prototype constructor for a class. Part of its job is dynamically creating a div that I want to stuff with responseText.
var divObj = document.createElement( "DIV" );
document.body.appendChild(divObj);
So then I tried to access divObj from inside the anonymous function. Guess what, all the attributes are null or undefined. Hmm. I tried all sorts of combos of stuff but no go. Finally I hit on something works.
var divObj = document.createElement( "DIV" );
document.body.appendChild(divObj);
divObj.name='foo';
var name=divObj.name;
Then I created an anonymous function and stuff it in a variable.
this.showResponse = function(transport) { $(name).innerHTML = transport.responseText;};
Prototype's $() function is a shortcut for document.getElementById(). Got that so far? Now just create the Ajax request.
var myAjax = new Ajax.Request(
url,
{
method: 'get',
parameters: paramstring,
onSuccess: this.showResponse
});
And go figure, that works. For some reason accessing an object in the anonymous function doesn't work, but a simple string does.
No comments:
Post a Comment