duanhongyi2964 2017-10-16 09:22 采纳率: 100%
浏览 84
已采纳

附加并处理从服务器返回的JS代码

I got a backend API written in PHP (w/ Laravel) which has one specific controller that receives an ID, makes a few DB actions to retrieve some data and then populates a dynamic js code (simply attaching it as a string to a variable, and returns it) based on the DB results and returns this code as a string.
On the client side though, what I'm willing to achieve is that on each entrance to the website, an ajax call will be sent to this API endpoint and a dynamic js piece of code will be attached to the DOM (and will be executed as well, of course).
For now, the API works well and returns the exact code that I'm willing, and on the client side I'm able to fetch it via a simple xhr request and attach it to the DOM, but the only problem is that it doesn't execute.

Current JS code for the API call:

<script>
    const url = 'http://127.0.0.1:8000/api/campaigns/1/1'; // get campaign

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.send();
    xhr.onreadystatechange = processRequest;

    function processRequest(e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
            let response = xhr.responseText;
            let div = document.getElementById('campaigns');
            div.insertAdjacentHTML( 'beforeend', response );
        }
    }
</script>

And the response is a string that contains a whole new script to be attached (and executed).

  • 写回答

2条回答 默认 最新

  • doupao6011 2017-10-16 09:30
    关注

    You can create script element dynamically every time you're receiving the code and append it in the body:

    <script>
        const url = 'http://127.0.0.1:8000/api/campaigns/1/1'; // get campaign
        var globalEval = eval;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.send();
        xhr.onreadystatechange = processRequest;
    
        function processRequest(e) {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let respondedJSCode = xhr.responseText;
                try {
                    if(respondedJSCode){
                        let script = document.createElement('script');
                        script.text = respondedJSCode;
                        document.body.appendChild(script);
                    }
                } catch (e) {
                    console.log(e);
                }
            }
        }
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样