Home  >  Article  >  php教程  >  wordpress中的php+ajax

wordpress中的php+ajax

WBOY
WBOYOriginal
2016-06-06 20:08:52957browse

以前是也整过异步,但我一直不知道wordpress可以自己处理自定义的AJAX回调请求,核心文件是 /wp-admin/admin-ajax.php .可以广泛运用在各处,这里给个实例吧,例子来自以前写的抓取网站第N条评论的作者,本文将以此为例介绍怎么在wordpress中用ajax异步调用PHP的f

以前是也整过异步,但我一直不知道wordpress可以自己处理自定义的AJAX回调请求,核心文件是/wp-admin/admin-ajax.php.可以广泛运用在各处,这里给个实例吧,例子来自以前写的抓取网站第N条评论的作者,本文将以此为例介绍怎么在wordpress中用ajax异步调用PHP的function.
记得前几天大发还问我,是不是觉得网站人气完犊子了?很明显确实完犊子了,你们这些没良心的,我就才忙了几天,人就跑光了,一点也不忠贞.
但是即使没有人看,代码还是要继续写的.
LIFE WILL GO ON EVEN U LEFT

JQ部分

function xhdAlert() {
	/** XHD AJAX BEGIN **/
	$.get(
		xhd_ajax_url, //ajax地址
		{ 
			action : 'get_4000th_ca',//调用的PHP function
			beforeSend: function() {  $('.oooo').text('Smallbutterfly loading');  } 
		},
		function( response ){
			$('.oooo').remove();
			if ( !response.error ) {
				alert ('The 4000th comment author of xiaohudie.net is ' + response.ca );//从PHP获取结果
			} else {
				alert ('error: ' + response.error );    
			}
		},
		"json" 
	);
} 

PHP部分

functions.php中加入如下代码

add_action( 'wp_ajax_nopriv_get_4000th_ca', 'get_get_4000th_ca' );
add_action( 'wp_ajax_get_4000th_ca', 'get_4000th_ca' );
function get_4000th_ca() {
	$comments = get_comments('number=1&offset=3999&order=ASC');
	header( "Content-Type: application/json" );
	foreach($comments as $comment) :
		echo json_encode( array('ca' => $comment ->comment_author) );//PHP获取的结果
		exit;//请求完成
	endforeach;
}

调用

<?php echo "<script>";
echo "var xhd_ajax_url = '" . admin_url( 'admin-ajax.php' ) . "'"; 
echo "" ;
?>
<a class="oooo" onclick="javascript:xhdAlert()">alert</a>

演示如下:

Click me!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn