Why doesn't embedded JavaScript execute when inserted in response to an ajax call?

后端 未结 2 340
北荒
北荒 2021-01-26 17:20

Inserting JavaScript in the .innerHTML does not cause it to run.

I have what I call a mini-feed in which a user submits a post. This initiates an ajax call which saves

相关标签:
2条回答
  • 2021-01-26 17:52

    The following code should work:

    function onSuccess() {
        src = document.createElement('script');
        src.innerHTML = this.responseText;
        document.body.appendChild(src);
    }
    

    But I would agree with cwallenpoole that why not have all that javascript code (for pretty-fying the date) be already written in advanced in the main page? (or script included or something).

    0 讨论(0)
  • 2021-01-26 18:12

    You're right, innerHTML will not do that, if you want to dynamically create a script tag, you will need to use document.createElement to create a script tag, but that has all of the same wonderful security bonuses associated with eval.

    Here's another idea, though. Wouldn't it be better to have some function defined in the main page which, after appending anything new, sets the date to "pretty" mode without needing to have the AJAX response know anything about it?

    0 讨论(0)
提交回复
热议问题