2012-09-22 88 views
0

我有以下的javascript如何获得HTML和JavaScript从响应

$.ajax({ 
    type: ... url: ... data: ... bla bla... 

    success: function(html) { 

     var response = $(html).filter('#targetID').html(); 

     $('body').html(response).show('slow'); 

    } 
}); 

它的工作原理,除了加载页面的JavaScript,JavaScript的在前看不见的罚款。 那么如何解决这个问题呢?

+1

如果您的脚本在body标签内,html()方法会清除所有内容,请考虑将数据附加到另一个元素而不是body元素。 – undefined

+0

'我有以下的javascript''$ .ajax({type:... url:... data:... bla bla ...'。那怎么执行? – Nope

+0

'javascript'是什么意思?消失“?它是否加载了页面? –

回答

0

你是说你正在通过Ajax请求获取JavaScript。

在这种情况下,您需要真正确保您有正确的代码。因为compability对这些事情来说是个婊子。 JQuery duos一个eval函数,我认为当他加载结果时,所以js应该加载。但可能是你的代码有一些通常在页面上被忽略的aprse错误,但是当你使用它和eval时,你会在某些浏览器中出错。

你使用哪个broser?

尝试在将代码加载到指定的div后对代码进行评估。

1

您应该在身体内部使用容器,而不要将代码直接放在身体中。

即。添加在体内的div标签,这将是集装箱

<div class="container"></div> 

然后在JS调用

$('.container').html(response).show('slow'); 

这样的内容加载在容器中,而不是直接在体内将取代所有该页面的内容包括你在那里的JS。

另外,当使用Ajax调用时,我认为它使得代码更清晰,将响应传递给其他函数进行处理。这样你将有更小的功能来调试和更容易理解的代码。

$.ajax({ 
    url: 'ajax/test.html', 
    success: function(data) { 

     //Here you pass the response to the other function 
     processSuccess(data); 
    }, 
    fail: function(data) { 

     //Here you pass the response to the other function 
     processFail(data); 
    } 

}); 

function processSuccess(response) { 
    //Print the response in the console (ie. Firebug console) 
    //if console is available 
    if(console) { 
     console.log(response); 
    } 
}; 

function processFail(response) { 
    //Print the response in the console (ie. Firebug console) 
    //if console is available 
    if(console) { 
     console.log(response); 
    } 
}; 

当然,在命名空间内的所有内容都会使它更好。

+0

没关系,但我需要只是响应的特定div,有时这个div可以包含javascript – chaplain