使用AJAX获取发布数据
我正在尝试学习AJAX和JSON,我在寻找合适的资源方面遇到了一些麻烦。 我还有很多问题,所以我主要是寻找资源。
我的目标是从wordpresspost中提取内容。 我尝试寻找教程和讨论,但我找到的解决方案对我不起作用或者我不喜欢,所以我不能正确理解我做错了什么。
到目前为止,我已将我的努力包括在内, 但这不是我的主要问题 。
加载的脚本。
wp_enqueue_script( 'my-ajax-request', get_stylesheet_directory_uri() . '/js/ajax.js', array( 'jquery' ) ); wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
JavaScript的
jQuery(document).ready(function($) { $('.ajax a').click(function(event) { event.preventDefault(); var id = $(this).data('id'); $.ajax({ type: 'POST', url: MyAjax.ajaxurl, data: {'action' : 'ajax_request', 'id': id}, dataType: 'json', success: function(data) { console.log(data); } }); return false; }); });
在这里,我设置了我的行动。 如何编码JSON并返回要使用的post数据?
add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request'); add_action('wp_ajax_ajax_request', 'ajax_handle_request'); function ajax_handle_request(){ }
通过设置全局$ post来获取$ post变量,我能够解决这个问题。
然后打印出$ response数组。
add_action('wp_ajax_nopriv_ajax_request', 'ajax_handle_request'); add_action('wp_ajax_ajax_request', 'ajax_handle_request'); function ajax_handle_request(){ $postID = $_POST['id']; if (isset($_POST['id'])){ $post_id = $_POST['id']; }else{ $post_id = ""; } global $post; $post = get_post($postID); $response = array( 'sucess' => true, 'post' => $post, 'id' => $postID , ); // generate the response print json_encode($response); // IMPORTANT: don't forget to "exit" exit; }
使用jQuery检索数据和输出。
jQuery(document).ready(function($) { $('.ajax a').click(function(event) { event.preventDefault(); var id = $(this).data('id'); $.ajax({ type: 'POST', url: MyAjax.ajaxurl, data: {'action' : 'ajax_request', 'id': id}, dataType: 'json', success: function(data) { console.log(data['post']); } }); return false; }); });
使用函数wp_send_json_success
和wp_send_json_error
返回Ajax请求结果。
它们都使用wp_send_json
,它负责标头,JSON编码和回显,并且死掉。
此外,您应该在本地化脚本时发送一个nonce:
array( 'url' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( "my_long_unique_string_name" ), )
并在wp_ajax_*
动作回调中检查它:
check_ajax_referer( 'my_long_unique_string_name', 'nonce' );
示例: https : //wordpress.stackexchange.com/a/106436/12615