[英]JavaScript with Ajax call to the WordPress API
I'm making a Wordpress plugin named "customposttype" that makes a custom post type with 3 custom fields.我正在制作一个名为“customposttype”的 Wordpress 插件,它使用 3 个自定义字段制作自定义帖子类型。 The plugin also must do an Ajax call to the WordPress API and gets all the data from those posts in JSON format, to show them in a specific template called "shoplist.php".
该插件还必须对 WordPress API 进行 Ajax 调用,并以 JSON 格式从这些帖子中获取所有数据,以在名为“shoplist.php”的特定模板中显示它们。
My CPT is called "tienda", it has this url for the REST API: ...wp-json/wp/v2/tiendas.我的 CPT 叫做“tienda”,它有这个 url 对于 REST API:...wp-json/wp/v2/tiendas。
I'm sure that I have several errors because it's my first time using an API and I'm very bad at Javascript.我确信我有几个错误,因为这是我第一次使用 API,而我在 Javascript 上的表现非常糟糕。
I'm stuck just right here, I don't know how to continue developing it.我被困在这里,我不知道如何继续开发它。
JS shows "Hello world," at the console. JS 在控制台显示“Hello world”。 but nothing else.
但没有别的。
PHP PHP
add_action("wp_ajax_nopriv_get_shop_data", "get_shop_data");
add_action("wp_ajax_get_shop_data", "get_shop_data");
function get_shop_data() {
$api_url = "https://pezquefuma.es/wp-json/wp/v2/tiendas";
$request = wp_remote_get($api_url);
$body = wp_remote_retrieve_body($request);
$output = json_encode($body, true);
echo $output;
die();
}
function my_enqueue() {
if ( get_page_template_slug() == 'shoplist.php' ) {
wp_enqueue_script( 'ajax-script', plugins_url('customposttype/js/filename.js'), array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('my-nonce')
)
);
}
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
JS JS
jQuery( document ).ready(function() {
console.log("Hello world!");
jQuery.ajax({
type : "GET",
dataType : "JSON",
url : my_ajax_object.ajax_url,
data : {
action: "get_shop_data",
},
error: function(response, error) {
console.log("wrong");
},
success : function(response) {
if(response.type === "success") {
console.log("Success");
}
}
});
});
There are two ways to check response data.有两种方法可以检查响应数据。 one is to use browser's.network devtool and another is to use console.log
一种是使用浏览器的.network devtool,另一种是使用console.log
success : function(response) {
console.log(response);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.