jQuery .load() / .ajax() not executing javascript in returned HTML after appended

喜你入骨 提交于 2019-11-26 13:48:39

When load() is used with a fragment selector the script element will be stripped out before the fragment is added thus the script will not get executed.

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:

So Try

$.get('partial.html', function(result){
    $result = $(result);

    $result.find('#content').appendTo('#new_content');
    $result.find('script').appendTo('#new_content');
}, 'html');

Demo: Fiddle

If you know what's the script you want to execute, you can define the script somewhere else, out of the ajax response, and then call it from the callback. So instead of:

$('#new_content').load(url+' #content > *',function() {alert('returned');});

you can use

$('#new_content').load(url+' #content > *',function() {my_function(my_param);});

How about this code,

$('#new_content').append($('<script>').html(source));

or you can simply move your JavaScript content to seperate file and load it using

$.getScript("url to js file");

or just use,

eval(source); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!