Skip to content

Instantly share code, notes, and snippets.

@terrylinooo
Created October 2, 2023 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terrylinooo/7965a9dfd1f3f10b2cbe102fc9d92586 to your computer and use it in GitHub Desktop.
Save terrylinooo/7965a9dfd1f3f10b2cbe102fc9d92586 to your computer and use it in GitHub Desktop.
ironman-simple-ajax.js
/**
* 測試 AJAX - 註冊 JS
*
* @return void
*/
function ironman_test_ajax_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script(
'ajax-demo',
get_template_directory_uri() . '/assets/js/ironman-simple-ajax.js',
array( 'jquery' ),
'1.0',
true
);
wp_localize_script(
'ajax-demo',
'demo_object',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
/**
* 測試 AJAX - 這裡註冊到鉤點中
*
* @return void
*/
function ironman_test_ajax_handler() {
echo '這是 2023 鐵人賽的範例唷!';
wp_die();
}
add_action( 'wp_enqueue_scripts', 'add_my_scripts' );
add_action( 'wp_ajax_test_action', 'ironman_test_ajax_handler' );
add_action( 'wp_ajax_nopriv_test_action', 'ironman_test_ajax_handler' );
jQuery(document).ready(function($) {
const demoObj = window.demo_object;
$('#simple-button').click(function() {
$.ajax({
type: 'POST',
url: demoObj.ajax_url,
data: {
action: 'test_action'
},
success: function(response) {
alert(response);
},
error: function() {
alert("發生錯誤");
}
});
});
});
<button id="simple-button">按這裡測試</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment