繁体   English   中英

如何在Ajax响应时执行javascript?

[英]How execute javascript at response from Ajax?

在我的Ajax响应中,有两个变量: jshtml

js变量内容标记脚本中的 Javascript://一些代码和html内容HTML模板。 如何从成功的响应Ajax执行html模板的js代码?

我尝试了以下解决方案:

$('head').append(response.js); // not works

完整的Ajax请求:

getFormShare: function(type){
        var posting = $.post('/share/getFormShare', { type : type } );

        posting.done(function( response ) {
            response = $.parseJSON(response);

            $("head").append(response.js);
            $('.ShareBlock #block').html(response.html).show();

            initFileUpload(config);
            initEditor();

        });
    }

PHP方面:

$js = $this->listdata->WrapperJavaScript($specialization, array('name_field' => 'type[]', 'tab' =>'tab', 'div_element' => '.specMain', 'label' => 'Category', 'autosearch' => 'true'));

$html = $this->load->view('social/forms/video', $this->data, true);
echo json_encode(array('html' => $html, 'js' => $js)); die();

您可以使用.getScript()并在加载后运行代码:

 $.getScript("my_lovely_script.js", function(){

    alert("Script loaded and executed.");
    // here you can use anything you defined in the loaded script

 });

您可以在此处看到更好的解释: 如何在另一个JavaScript文件中包含一个JavaScript文件?


编辑:由于您要返回实际的javascript并想执行它,因此可以在ajax响应中简单地执行此操作:

 $.get(url,function(data){ $("body").append(data); });

编辑:在迈克的答案的帮助下,如果您的响应中没有脚本标签,则可以使用eval()运行脚本。 他的回答提供了更多有关此的信息。

您可以利用javascript的eval将字符串作为代码运行。

请记住,您的字符串必须是纯JS,没有html或其他元素。

eval("function foo() {console.log('bar');}");
//this call will create/instantiate a function called foo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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