How can I dynamically load and execute Javascript from the server without using eval ()?

I am writing a PHP framework that allows PHP developers to create ExtJS interfaces with forms, grids, tabs and menus using PHP classes only.

To create a TabPanel, for example, a PHP class is created with an array of URLs that load dynamically when the user clicks on the tab title.

To do this, I use the following Javascript function, which loads a PHP page through an AJAX call and runs any scripts inside it.

function loadViewViaAjax(url) {
    Ext.Ajax.request({
        url: url,
        success: function(objServerResponse) {
            var responseText = objServerResponse.responseText;
            var scripts, scriptsFinder=/<script[^>]*>([\s\S]+)<\/script>/gi;
            while(scripts=scriptsFinder.exec(responseText)) {
                eval(scripts[1]);
            }
        }
    });
}

, eval(), do eval() . , PHP, AJAX, , , , , .

javascript eval(), , , script, .. TabPanels, Javascript ?

+3
3

Javascript script. script DOM, script . :

var newScript = document.createElement('script'); 
newScript.setAttribute('src', 'http://www.example.com/url/of/your/script.php'); 
document.body.appendChild(newScript); 

, "JSONP".

+7

URL- ( ). URL- . , :

var head = document.getElementsByTagName('head').item(0);
var script = document.createElement('script');
    script.language = "javascript";
    script.type = "text/javascript";
    script.id = "script-id";
    script.defer = true;
    script.text = source;

    head.appendChild(script);

, .

0

eval, , .

var body = "you source here";

var f = Function(body);

f();

This can be used to load reusable code segments.

0
source

Source: https://habr.com/ru/post/1781615/


All Articles