TODO: To change the header's content go to Dr.Explain menu Options : Project Settings : HTML (CHM) Export : Setup HTML Template and Layout
×
Menu
Index

Tạo sử lý ajax riêng

 
Một cách làm khác khi sử lý ajax là tạo file php riêng, điều này sẽ tránh load những thành phần không cần thiết hay chúng không bao giờ sử dụng cho ajax. Điều này giúp thời gian truy vấn nhanh hơn. Bạn chỉ cần nhúng môi trường Wordpress vào file và tạo tùy biến action.
 
Tùy biến action:
Xem đoạn code mẫu sau đây:
File: my_custom_ajax.php
<?php
    //mimic the actuall admin-ajax
    define('DOING_AJAX', true);
 
    if (!isset( $_POST['action']))
        die('-1');
 
    //make sure you update this line
    //to the relative location of the wp-load.php
    require_once('../../../wp-load.php');
 
    //Typical headers
    header('Content-Type: text/html');
    send_nosniff_header();
 
    //Disable caching
    header('Cache-Control: no-cache');
    header('Pragma: no-cache');
 
/*Next we need to call the actual methods we want to invok*/
    $action = esc_attr(trim($_POST['action']));
 
    //A bit of security
    $allowed_actions = array(
        'custom_action1',
        'custom_action2'
    );
 
    //For logged in users
    add_action('SOMETEXT_custom_action1', 'handler_fun1');
    add_action('SOMETEXT_custom_action2', 'handler_fun1');
 
    //For guests
    add_action('SOMETEXT_nopriv_custom_action2', 'handler_fun2');
    add_action('SOMETEXT_nopriv_custom_action1', 'handler_fun1');
 
    if(in_array($action, $allowed_actions)) {
        if(is_user_logged_in())
            do_action('SOMETEXT_'.$action);
        else
            do_action('SOMETEXT_nopriv_'.$action);
    } else {
        die('-1');
    }
 
?>
 
Sửa chuỗi "SOMETEXT" để phân biệt mang thương hiệu của bạn.
Chú ý:
- Nếu bạn muốn cache kết quả ajax thì sử dụng:
header("Cache-Control: max-age=2592000"); //30days (60sec * 60min * 24hours * 30days)
 
Tạo js gọi ajax.
Lúc này địa chỉ ajax không phải là admin-ajax.php mà chuyển sang file my_custom_ajax.php
wp_localize_script( 'some-script', 'some_variable', array( 'customajax' => plugins_url('my_custom_ajax.php' , __FILE__) ) );
 
Gửi yêu cầu ajax.
var data = {
  action: 'custom_action1',
  something: 'something'
};
var x = $.post(some_variable.customajax, data, function(response) {
    console.log(response);
});
Made with help of Dr.Explain

Unregistered version