-
-
Save terrylinooo/7965a9dfd1f3f10b2cbe102fc9d92586 to your computer and use it in GitHub Desktop.
ironman-simple-ajax.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 測試 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' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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("發生錯誤"); | |
} | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<button id="simple-button">按這裡測試</button> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment