gpt4 book ai didi

jquery - AJAX WordPress 网址

转载 作者:行者123 更新时间:2023-12-01 04:49:01 24 4
gpt4 key购买 nike

我在使用 AJAX 时遇到问题。

jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php", // our PHP handler file
data: "myDataString",
success:function(results){
alert(results);
}
)};

未经授权,此请求无效。如何在 WP 中添加自定义 URL 到操作?

最佳答案

问题不是很清楚,但是我会帮助您为登录和未登录用户添加 AJAX 操作。

// Add this to functions.php
// Let's enqueue our javascript file
function include_ajax_js() {

wp_register_script(
'ajax-custom-script',
get_stylesheet_directory_uri() . '/js/ajax.js',
array( 'jquery' )
);

// Add data your script that you can normally
// only get from the server side of WordPress.

$localize = array(
'ajaxurl' => admin_url('admin-ajax.php'),
// Securing your WordPress plugin AJAX calls using nonces
'auth' => wp_create_nonce('_check__ajax_100')
);
wp_localize_script('ajax-custom-script', 'custom_ajax_vars', $localize);

wp_enqueue_script('ajax-custom-script');

}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

// Let's make function to handle AJAX requests
function my_ajax_action() {

// Check nonce
check_ajax_referer( '_check__ajax_100', 'nonce_field' );

// Let's display some useful information
// May be you need to check if the user is still logged in

$user_greeting = is_user_logged_in() ? 'Hello User !' : 'Hello Guest !';
$data = array( 'msg' => $user_status );

echo json_encode($data); // encode the output to JSON
die();
}
add_action( 'wp_ajax_check_status', 'my_ajax_action' );
// wp_ajax_nopriv_ executes for users that are not logged in
add_action( 'wp_ajax_nopriv_check_status', 'my_ajax_action' );

现在 PHP 已经足够了,让我们创建 ajax.js

jQuery(document).ready(function(){

jQuery.ajax({
type:"POST",
// We can easily get the AJAX Url from the object we've created before
url: custom_ajax_vars.ajaxurl,
// Data should be sent as an object
data: { action: check_status, nonce_field: custom_ajax_vars.nonce },
success:function(data){
alert(data.status);
}
)}
})
})

关于jquery - AJAX WordPress 网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24177964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com