简体   繁体   中英

Calling a user defined JS function inside returned AJAX content

I have a system that loads a div with content through the use of AJAX. All is well, I can get the div to load perfectly with details from my database and it works great.

The problem is this:

Inside the returned div, I have a couple of buttons with onClick events. The onClick events cause an error when I attempt to call a user defined function onClick="my_function();" but the onClick events do not cause an error when I call a JS defined function onClick="alert('success');" .

Anyone know why this would be? my_function() is defined in the head of my page. Although, I have also tried to define it in the content returned by AJAX, still with no luck.

Any help will be greatly appreciated

if you are using prototype, jquery, etc.. (any JS framework), you need to be sure you have set the param "evalJS" to true. this last example I put works in prototype.

check here for prototype

You could try adding event handlers via JavaScript instead of onclick handlers on the actual elements.

Then you could use anonymous functions.

If you're simply updating the innerHTML of a DIV element with the result of an AJAX request, keep in mind that the browser parses only HTML not scripts.

Probably that's why you're recieving the JavaScript Error.

To parse also the scripts you need to consult the documentation of your library. For instance, if you're using ASP.NET you can call ScriptManager.RegisterClientScriptBlock in order to instruct the AJAX client componenet to parse the scripts in the result.

On the other hand, if you're doing it by hand (one thing I did awhile back), you need to detect and parse the scripts yourself.

OK, here is the simple answer.. I had the button element name and id as the same as the function which it was trying to call.. stupid mistake I know.. anyhow, it is now working.. however, I do have another problem.. my ajax only fires once.. it works great the first time, but after that the function doesn't work

here is my code:

function delete_account(account_id) {
  create_request();
  var url = "accounts_ajax.php?action=delete_account&account_id=" + account_id;

  show_div('action_window');

  document.getElementById('action_window').innerHTML = '<div class="please_wait"><img src="images/working.gif"><br>Loading...</div>';  

  xmlHttp.open("GET", url, true);
  xmlHttp.onreadystatechange = function(){if(xmlHttp.readyState!=4)return;if(xmlHttp.status==200){reload_div('action_window', xmlHttp.responseText);}};
  xmlHttp.send(null);
  }

it just causes an error second time around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM