作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的 Ajax 响应中,有两个变量:js、html。
标签script中的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
});
您可以在这里看到更好的解释:How do I include a JavaScript file in another JavaScript file?
<小时/>编辑:由于您要返回实际的 javascript 并希望执行它,因此您可以简单地在 ajax 响应中执行此操作:
$.get(url,function(data){ $("body").append(data); });
编辑:在 Mike 的回答的帮助下,如果您的响应中没有脚本标记,您可以使用 eval()
来运行脚本。他的回答提供了更多相关信息。
关于javascript - 如何在 Ajax 响应时执行 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25849978/
我是一名优秀的程序员,十分优秀!