[英]Javascript function after ajax call
I'm trying to call to a JavaScript function that is sent in a Ajax call 我正在尝试调用在Ajax调用中发送的JavaScript函数
What is the correct way to execute a JavaScript function returned from an Ajax call? 执行从Ajax调用返回的JavaScript函数的正确方法是什么?
Let say the script looks like this before the Ajax call 假设脚本在Ajax调用之前看起来像这样
<script>
function start(){
console.log('1');
}
</script>
I receive 我收到
<script>
function start(){
console.log('2');
}
</script>
Here is the code I have now 这是我现在的代码
nav = $('.js-as'),
$content = $('.js-content'),
$status = $('.js-status'),
$script = $('.js-script'),
$.ajax({
url: '/ajax',
cache: false,
beforeSend: function() {
if (isSupported('transition')) $status.removeClass('start done');
fadeTimer = setTimeout(function() {
if (isSupported('transition')) $status.addClass('start');
}, 100); // Avoid fadeTimer() if content already in cache
},
success: function(data) {
if (fadeTimer) clearTimeout(fadeTimer);
$nav.removeClass('selected');
stateLink(e, 'active');
handler(data);
}
});
handler = function(data) { // Response
d.title = data.pagetitle;
$content.html(data.content);
$script.html(data.script); // my new script
eval(start()); // execute it
};
UPDATE: Solution Using jQuery.globalEval solved this issue 更新:解决方案使用jQuery.globalEval解决了此问题
Use one function with argument. 将一个函数与参数一起使用。
Something like that: 像这样:
<script>
function start(num){
console.log(num);
}
</script>
So before the AJAX call tou can call start(1)
and after the AJAX call you can call start(2)
因此,在AJAX调用之前,tou可以调用start(1)
而在AJAX调用之后,您可以调用start(2)
var start = function(){
console.log(1);
}
After ajax calling 在ajax调用之后
start = function(){
console.log(2);
}
start();
// output "2"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.