admin-ajax.php
是WordPress的一部分AJAX API, 是的,它确实处理来自后端和前端的请求。以下是我对你的问题的理解:
2) 如何管理ajax。php工作?
对于logic 你可以参观这里。
这假设您已经知道如何将JavaScript等排入队列。
JavaScript Piece:
jQuery(document).ready(function($) {
// We\'ll pass this variable to the PHP function example_ajax_request
var fruit = \'Banana\';
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
\'action\':\'example_ajax_request\',
\'fruit\' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
PHP Piece:
function example_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST[\'fruit\'];
// Let\'s take the data that was sent and do something with it
if ( $fruit == \'Banana\' ) {
$fruit = \'Apple\';
}
// Now we\'ll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you\'re debugging, it might be useful to see what was sent in the $_REQUEST
// print_r($_REQUEST);
}
// Always die in functions echoing ajax content
die();
}
add_action( \'wp_ajax_example_ajax_request\', \'example_ajax_request\' );
// If you wanted to also use the function for non-logged in users (in a theme for example)
add_action( \'wp_ajax_nopriv_example_ajax_request\', \'example_ajax_request\' );
1)为什么要使用管理ajax。php,而不是在单独的文件(如主题/示例/json)中编码json。php并在那里对数据进行编码?
这可能会有帮助。admin-ajax.php vs Custom Page Template for Ajax Requests