2012-09-22 83 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