問題描述
我向 TinyMCE 編輯器新增了一個自定義按鈕,當我點選它時,我想開啟 WP 的 Thickbox 。
如何使 tb_show()功能載入我想要的內容與 ajax?
// the ajax
add_action('wp_ajax_getTheContent', 'getTheContent');
function getTheContent(){
echo 'weqwtegeqgr'; // <- this should be displayed in the TB
die();
}
這是我使用的一些編輯器外掛程式碼:
init : function(ed, url) {
ed.addButton('do_stuff', {
title : 'Do Stuff',
image : url + '/icon.gif',
onclick : function() {
OpenMyThickbox('do_stuff');
}
});
...
所以 OpenMyThickbox javascript 函式應該做我想要的:
function OpenMyThickbox(tag){
tb_show(tag, '...'); // <- how to load content trough ajax here ?
}
最佳解決方案
tb_show 的第二個引數是 URL,所以你想要使用像
<?php
$ajax_url = add_query_arg(
array(
'action' => 'getTheContent',
'query_var1' => 'value1',
'query_var2' => 'value2'
),
admin_url( 'admin-ajax.php' )
);
?>
tb_show(tag, <?php echo $ajax_url; ?> );
我猜想你需要手動傳遞動作和任何其他查詢變數 (如上所述),否則您的請求僅適用於 admin-ajax.php,當您要查詢的內容與… admin-ajax.php?action=getTheContent&someothervar=someothervalue 相符時,因此 add_query_arg 使用上述..
澄清:
以下呼叫 add_query_arg …
add_query_arg(
array(
'action' => 'getTheContent',
'query_var1' => 'value1',
'query_var2' => 'value2'
),
admin_url( 'admin-ajax.php' )
);
相當於並將產生…
http://example.com/wp-admin/admin-ajax.php?action=getTheContent&query_var1=value1&query_var2=value2
然而!
現在已經解釋了自己,我已經意識到我們不想要絕對 URL,因此不需要呼叫 admin_url 。程式碼應該是。
<?php
$ajax_url = add_query_arg(
array(
'action' => 'getTheContent',
'query_var1' => 'value1',
'query_var2' => 'value2'
),
'admin-ajax.php'
);
?>
tb_show(tag, <?php echo $ajax_url; ?>);
所以產生的 URL 看起來像這樣..
admin-ajax.php?action=getTheContent&query_var1=valu1&query_var2=value2
以上程式碼示例中引用的函式:
-
新增查詢 Arg http://codex.wordpress.org/Function_Reference/add_query_arg
-
管理網址 http://codex.wordpress.org/Function_Reference/admin_url
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。