简体   繁体   中英

JavaScript function is loaded via Ajax but not executed?

I have different websites that have the same data protection. So that the text does not have to be changed every time on all pages, there is a file on another server that is integrated via Ajax.

There is a part where you can set an opt-out and the domain of the respective page must be stored there.

<a href="#" id="setOptOut">I don't want to get tracked!</a>
<script type="text/javascript">
  document.getElementById("setOptOut").addEventListener('click', function(e) {
    e.preventDefault();
    var redirect = 'https://' + window.location.hostname + '/privacy';
    var url = encodeURIComponent(redirect);
    location.href = url;
  });
</script>

The code above which is in an HTML file is loaded successfull via Ajax into the document of the web page, but when I click on the link the function is not executed.

If I call the HTML file directly on the server, everything works as expected. Why doesn't it work with Ajax?

Found this good example:https://subinsb.com/how-to-execute-javascript-in-ajax-response/

I used eval() to make the code in the AJAX response execute.

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