WordPressでAjaxを実現する方法

56889 ワード

多くのWordpressのテーマとプラグインにはAjaxが使われているが、すべてのテーマとプラグインが適切な方法でAjaxを実現しているわけではない.Ajaxには何か特定の方法が必要なのか不思議に思うかもしれません.Wordpressにおいて、WordPressはAjaxを実現するために安全で有効な方法を提供した.これは長い文になります.次のリンクはジャンプしやすいです.
よくないAjaxはを実現します
wp_の使用localize_script()javascriptグローバル変数を宣言する
admin-ajaxを使用します.phpはAjax要求を処理する.
noncesを使用してパーミッションを確認
Wordpressに組み込まれたjQuery Form pluginを使用してフォームを発行
あまり良くないAjax実装
多くのプラグインが実現する可能性があります
require_once( "../../../../wp-config.php" );
// or require_once( "../../../../wp-load.php" );

このようなデメリットは多く、ユーザが設定ディレクトリが異なると相対経路が失効する.また、プラグインでオブジェクト向けの書き方を使用している場合は、変数やプライベートメソッドを直接使用することはできません.最大のデメリットは、Wordpress全体のフレームワークを追加して再ロードすることです.
wp_の使用localize_script()はjavascriptグローバル変数を宣言します
これは偉大な関数です.
wp_localize_script( $handle, $namespace, $variable_array );

例えば、Ajaxリクエストを処理するためにURLを宣言します.
//     AJAX   js  
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
 
//       Ajax   URL,        (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

このようなやり方はそれほど醜くない...今から見れば html , :
<script type="text/javascript" src="http://hongwei.im/wordpress/wp-content/plugins/myajax/js/ajax.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
var MyAjax = {
ajaxurl: "http://hongwei.im/wordpress/wp-admin/admin-ajax.php"
};
/* ]]> */
</script>

admin-ajax.php Ajax

Ajax wp-admin/admin-ajax.php、ファイル の「admin」は するかもしれないが、フロントでもバックグラウンドでもAjaxリクエストはadmin-ajax.phpで されている.admin-ajax.phpにリクエストを する 、actionという パラメータがあります.admin-ajax.phpは、ユーザーがログインしたかどうかによって なるhooksをトリガーする があるからです.

//      ,      hook
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
 
//      ,      hook
do_action( 'wp_ajax_' . $_POST['action'] );

Ajaxリクエストを するコードは、 のようになります.
jQuery.post(
       MyAjax.ajaxurl,
       {
            action : 'myajax-submit',
            postID : MyAjax.postID
       },
       function( response ) {
            alert( response );
       }
);

これで、テーマファイルでAjaxリクエストを するだけで、 のファイルで する はありません.
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );
 
function myajax_submit() {
	$postID = $_POST['postID'];
	$response = json_encode( array( 'success' => true ) );
 
	header( "Content-Type: application/json" );
	echo $response;
 
	//          :     "exit"
	exit;
}

noncesと の
を するのは には わしいことがあります. にあなたが する で、 と がかかりますが、 のコントロールは かに で、あなたのウェブサイトの を することができます.Ajaxリクエストを するには、2つの を する があります.
Nounces
Noncesは する のセットであり、 しか できないので、Ajax ソースの を するために することができる.Noncesの について、ここに い がありますNonce-It’s like the deli counter、この は き きとしています.
When you arrive at a deli counter you’re asked to take a ticket. Once the counter reaches your number you had the ticket back to the server (who throws it away) and they serve you. They then move onto serving the next person in the who’s ticket matches the number of the digital screen.
If someone comes along and tries to jump the line (queue) they can’t unless they have a ticket.
If they manage to get hold of someones old ticket, they can’t use it, as it’s already been used and the digital counter has moved on.
To further extend the analogy, you then make every customer sign for the ticket when they take one, and you then check not only that there ticket matches but also make them sign again to check that their first signature matches the one they have before they get served.
Taking it to a silly level, you’d only allow users to get a ticket when they walked in the front door of the store (that they have to sign for). This then prevents someone climbing in a window and trying to forge your signature to get served. Because they didn’t come in the front door, they don’t have any access to the tickets, so they have no way of jumping ahead of you and ordering the last of the Bologna.
しなければならないのは、すべての 、Noncesを する はありません.Ajaxリクエストがデータやコンテンツを するために されている は、Noncesを する があります.Ajaxリクエストがデータを み すだけであれば、Noncesを する はありません.どのように いますか?まずnonceを し、wp_localize_script()でjavascriptの に します.
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
 
wp_localize_script( 'my-ajax-request', 'MyAjax', array(
	'ajaxurl' => admin_url( 'admin-ajax.php' ),
 
	//     ID  "myajax-post-comment-nonce"  nonce
	'postCommentNonce' => wp_create_nonce( 'myajax-post-comment-nonce' ),
	)
);

Javascriptコードでは、グローバル MyAjax.postCommentNonceを してnonceを できます.Ajaxリクエストとともにnonceを する があります.
jQuery.post(
	MyAjax.ajaxurl,
	{
		action : 'myajax-submit',
		postID : MyAjax.postID,
 
		postCommentNonce : MyAjax.postCommentNonce
	},
	function( response ) {
		alert( response );
	}
);

nonceは い てであることに する、 しいnonceを するたびに、 いnonceは の に する.
アクセス
コードにアクセスして、 をチェックする を てみましょう.
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );
 
function myajax_submit() {
 
	$nonce = $_POST['postCommentNonce'];
 
	if ( ! wp_verify_nonce( $nonce, 'myajax-post-comment-nonce' ) )
	die ( 'Busted!')
 
	if ( current_user_can( 'edit_posts' ) ) {
 
		$postID = $_POST['postID'];
 
		$response = json_encode( array( 'success' => true ) );
 
		header( "Content-Type: application/json" );
		echo $response;
	}
 
	exit;
}

WordPressに み まれたjQuery Form pluginを してフォームをコミット
まだ らない もいるかもしれませんが、WordPressはフォームのAjaxコミットを するためにjQueryプラグインを しています.それはjquery-formがどのようにロードするかということです. の を てください.
jQuery('#myForm1').ajaxForm({
	data: {
		//  
	},
	dataType: 'json',
	beforeSubmit: function(formData, jqForm, options) {
		//          
	},
	success : function(responseText, statusText, xhr, $form) {
		//        
	}
});

いいえ、ありません. にありません.