如何在WP自定义函数中使用$ .ajax?



我正在使用Wordpress,我想在我的自定义函数中使用jQuery$.ajax()函数.php子主题中的文件。我是WP的新手,所以我没有任何想法如何在WP中使用jQuery AJAX。

我不知道 JSON 数据来自的函数的 URL 是什么。请帮忙

<div class="rig-textGrid" style="cursor: pointer" data-toggle="modal" data-target="#myModal" onclick="GetDetailsCat('.$cat_id.')">'.$name.'</div>
function GetDetailsCat(cat_id) {
data = "";
url = "";
data = "&cat_id=" + cat_id;
url = "";
$.ajax({
data: data,
type: "get",
url: url,
dataType: "json",
error: function(resp) {
alert("Somthing Went Wrong !!!");
},
success: function(resp) {}
});
}

像这样 你可以在函数中编写 GetDetailsCat(.php

<?php  
function load_script_to_get_data(){
?>
<script>
function GetDetailsCat(cat_id) {
$.ajax({
type: "post",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
dataType: "json",
data : { action: "get_data", cat_id: cat_id }
error: function(resp) {
alert("Somthing Went Wrong !!!");
},
success: function(resp) {
}
});
}
</script>
<?php
}
add_action( 'wp_footer', 'load_script_to_get_data' );

寻找这个解决方案。我想它肯定会帮助你。 要在 Wordpress 中运行 ajax 在 ajax URL 中,您需要提供 admin-ajax URL,即 admin_url('admin-ajax.php'( 接下来,您需要在属于函数.php函数的数据中发布一个操作

function GetDetailsCat(cat_id) {
$.ajax({
type: "post",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
dataType: "json",
data : { action: "get_data", cat_id: cat_id }
error: function(resp) {
alert("Somthing Went Wrong !!!");
},
success: function(resp) {
}
});
}
functions.php 
add_action( 'wp_ajax_get_data', 'get_data' );
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
function get_data() {
$cat_id= esc_attr ($_POST['cat_id ']);
$result = "Your custom code which you want to do run";
echo  $result; //return value
die();
}

最新更新