2012-06-28 57 views
0

我想使用AJAX調用從同一頁面檢索HTML和Javascript。但是,我不確定最佳,最乾淨和最安全的方法是什麼。我想讓我的Javascript編輯客戶端上已定義的對象。到目前爲止,我的想法是:如何通過Ajax發送HTML和Javascript

一些事件執行客戶端腳本:

getMoreStuff = function() { 
    $.ajax({ 
    url: '/someRoute', 
    success: function (data) { 
     $data = $(data); 
     $things = $data.find('#things'); 
     $('#content').append($things); 
     // Execute the script 
    } 
    }) 
} 

AJAX請求的身體:

<div id="things"> 
    <div class="post">...</div> 
    <div class="post">...</div> 
    <div class="post">...</div> 
    <div class="post">...</div> 
    <div class="post">...</div> 
</div> 
<script> 
    (function() { 
    window.things || (window.things = []); 
    things.concat([...some array...]); 
    })(); 
</script> 

我不知道如果我的jQuery代碼執行它當我定義$data。或者我應該將腳本作爲字符串發送並使用eval?

會這樣嗎?

$(document.body).append($data.find('script')); 
+0

什麼是文件中的事情數組的性質是你從哪裏發射ajax和什麼'concat'ed它呢? – prodigitalson

回答

2

見的dataType here

「HTML」:返回HTML純文本;包含的腳本標記在插入DOM時評估爲 。

+0

謝謝,簡單的回答。從來沒有使用'dataType',但我想我不需要,因爲它會自動和正確地推斷我的內容爲HTML。 –

+0

是的,只要mimetype是正確的。我並不是說你需要** dataType,但我只是想告訴你引用/文檔的來源。 – WhyNotHugo