星期一, 8月 01, 2016

[Wordpress] 如何ajax來呼叫 php function

記錄一下如何在wp操作ajax function呼叫php function,意思就是你可以透過hook機制寫自已的api嚕

官網的sample說明


  • action命名規則wp_ajax_[你的方法]
  • action function 命名規則 [你的方法]_callback
tips: 請注意你的方法命名不可以長的不一樣,會無法對應呼叫

add_action( 'wp_ajax_my_action', 'my_action_callback' );

function my_action_callback() {
 global $wpdb; // this is how you get access to the database

 $whatever = intval( $_POST['whatever'] );

 $whatever += 10;

        echo $whatever;

 wp_die(); // this is required to terminate immediately and return a proper response
}

在頁面render一個jquery的方法(因為是範例所以方法很簡單,page_load之後就打)可以搭配admin_enqueue_scripts來整理你自已外掛所需的js
 jQuery(document).ready(function($) {

  var data = {
   'action': 'my_action',
   'whatever': 1234
  };

  // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
  jQuery.post(ajaxurl, data, function(response) {
   alert('Got this from the server: ' + response);
  });
 });

參考

https://codex.wordpress.org/AJAX_in_Plugins

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails