how do I return a javascript statement to the ajax responseText
For example:
In the HTML page
xmlHttpObj.open("GET", "url.php", true);
xmlHttpObj.onreadystatechange = function(){
..
document.getElementById('divInThisPage').innerH开发者_如何学CTML = xmlHttpObj.responseText;
..
}
..
..
function foo(arg){
alert(arg);
}
In the url.php
echo "<input type='button' value='ok' onclick=\"foo('ok')\" />";
The question is, why the alert won't work?
edit: even if in the url.php I put a inline javascript code the button still doesn't work
echo "<input type='button' value='ok' onclick=\"alert('ok')\" />";
I think what you are asking is why, when you click the button that has been created by your ajax request, the alert is not alerting. This is probably because the onclick event handler foo()
has not been registered. This I think is browser dependent - try in a different browser and it may work.
Anyway it's not working because when you dynamically add HTML to a page like this the onclick is not being registered in your browser. You can add event listeners to an element like this:
function doAddEventListener(elem, eventName, fn) {
if(elem.addEventListener ) {
elem.addEventListener(eventName, fn, false);
} else if (elem.attachEvent) {
elem.attachEvent('on'+eventName, fn);
}
}
where fn
is the function you want to add, i.e foo
, and eventName
in this case would be "click", and elem
is the element you want to add the listener to.
Just tried the same code on FF3 and it seems to work just fine. Are you sure there is no typo somewhere? Try using firebug for clues.
精彩评论