2010-10-24 49 views
1

下面返回該字符串的jQuery函數:這裏需要什麼需要在jQuery ajax post函數中按原樣執行ajax服務器響應?

'#prayer_date'.html("03/19/1968"); 

但是它沒有得到執行,因爲下面的功能上不data變量行事。

你需要做什麼才能使結果在下面的函數中按原樣執行?

$('.showprayer').click(function(event) 
{ 
    $.post('/show_prayer', { 'name' : $(this).text() }, function(data) 
    { 
     // how to execute the `data` server response as-is? 
    }); 
}); 

回答

1

您的迴應將需要有效的腳本首先,像這樣:

$('#prayer_date').html("03/19/1968"); 

然後在你的功能,你可以調用eval(),像這樣:

$('.showprayer').click(function(event) { 
    $.post('/show_prayer', { 'name' : $(this).text() }, function(data) { 
    eval(data); 
    }); 
}); 

.... 但這幾乎從來都不是一個好的解決方案,可能有更好/更直接的路線來做你的事情。一個稍微好一點/更安全的解決方案是使用擴展$.ajax()形式爲全球的eva​​l,像這樣:

$('.showprayer').click(function(event) { 
    $.ajax({ 
    url: '/show_prayer', 
    type: 'POST', 
    data { 'name' : $(this).text() }, 
    dataType: 'script' 
    }); 
}); 

不同的是,這裏使用jQuery.globalEval()其粘腳本在<head>,就好像它是一個正常的GET請求<script>,而不是實際上調用eval()就可以了。