使用jQuerysgetJSON
在autocompletes源代码方法中,使用WordPress的admin ajax。php来处理请求,以避免必须查找wp负载。php(可能已被移动),并将在每次请求时加载WordPress。
First of all: get the ajax url of your WordPress blog:
这很简单:
admin_url( \'admin-ajax.php\' )
但是,我们希望在您的javascript文件中可以访问它,所以请使用
wp_localize_script
wp_enqueue_script( \'myajax_jsfile_handle\', get_stylesheet_directory."/rest/of/path/to/file.js", array( \'jquery\', \'jquery-form\', \'json2\' ), false, true ); );
wp_localize_script(
\'myajax_jsfile_handle\',
\'MyAjax_object\',
array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
\'myajax_nonce\' => wp_create_nonce( \'myajax_nonce_val\' ),
\'action\' => \'myajax-submit\'
)
);
在哪里
myajax_jsfile_handle
是您注册的javascript文件的句柄。当您对javascript文件进行排队时,请调用上述命令。
The autocomplete source method
对于JQuery UI自动完成选项中的源。。。
source: function( request, response ) {
jQuery.getJSON( MyAjax_object.ajaxurl + "?callback=?&action=myajax-submit", request, function( data ) {
response( jQuery.map( data, function( item ) {
jQuery.each( item, function( i, val ) {
val.label = val.whatever; // build result for autocomplete from suggestion array data
} );
return item;
} ) );
} );
},
request
是键入的内容动作是Wordpress解释的(见下文)。这些添加了autcomplete用于返回建议的url
上面所做的是获取每个项目(返回的JSONrd行)并给它们一个标签,autocomplete使用该标签来显示建议。(在上面的示例中,标签是“column”列的内容)
Tell WordPress how to do deal with the request
因此,上面向WordPress发送了一个ajax请求,操作为“myajax提交”。
当WordPress收到此消息时,它会触发操作wp_ajax_myajax-submit
(如果用户已登录)或wp_ajax_nopriv_myajax-submit
如果他们不是。您可以将函数挂钩到其中一个或两个挂钩上,具体取决于您打算允许此AJAX请求的对象。我们的函数将执行任何必要的查询和JSON结果(建议)并响应它们。
// Callback
function get_my_suggestions() {
// This function should query the database and get results as an array of rows:
// GET the recieved data: \'term\' (what has been typed by the user)
$term = $_GET[\'term\']
$suggestions_array = array();
// echo JSON to page and exit.
$response = $_GET["callback"]."(". json_encode($suggestions_array) .")";
echo $response;
exit;
}
add_action( \'wp_ajax_myajax-submit\', \'get_my_suggestions\' );
//For non-logged in users add_action( \'wp_ajax_nopriv_myajax-submit\', \'get_my_suggestions\' );
免责声明:该示例在任何情况下都返回空数组