我正在用WooCommerce构建一个WordPress站点,并且我还为我的小商店制作了一个HTML5应用程序。我的愿望是从我的HTML5应用程序通过Ajax调用Wordpress函数(例如研究),并在商店中获得结果与合作图像。我在谷歌上找到它,但没有什么有趣的...从客户端使用Ajax调用Wordpress函数
谢谢。
我正在用WooCommerce构建一个WordPress站点,并且我还为我的小商店制作了一个HTML5应用程序。我的愿望是从我的HTML5应用程序通过Ajax调用Wordpress函数(例如研究),并在商店中获得结果与合作图像。我在谷歌上找到它,但没有什么有趣的...从客户端使用Ajax调用Wordpress函数
谢谢。
首先,你必须确保你可以动态获取的WordPress admin-ajax.php
URL(从来没有硬编码的,除非你的HTML5应用是不是WordPress的商店的一部分)。要做到这一点,它添加到你的主题functions.php
:
function so46065926_scripts() {
wp_enqueue_script('so46065926-ajax', get_theme_file_uri('assets/js/ajax.js'), array('jquery'));
// Make the Ajax URL available in your ajax.js
wp_localize_script('so46065926-ajax', 'so46065926', array(
'ajaxURL' => admin_url('admin-ajax.php'),
));
}
add_action('wp_enqueue_scripts', 'so46065926_scripts');
然后你就可以创建一个让你需要的信息的功能。你可以在这里使用WooCommerce功能,因为你对你functions.php
function so46065926_research() {
$form_data = $_POST['formData']; // The parameter you sent in your Ajax request.
/**
* Anything you echo here, will be returned to your Ajax.
* For instance, a template part, and that template part
* can contain the product image.
*/
get_template_part('template-part/content', 'product-research');
wp_die(); // Don't forget to add this line, otherwise you'll get 0 at the end of your response.
}
add_action('wp_ajax_research', 'so46065926_research');
add_action('wp_ajax_nopriv_research', 'so46065926_research');
然后,你就可以建立你的客户端脚本。它可能是这样的:
jQuery(document).on('submit', '.research-form', function(event) {
event.preventDefault();
var formData = jQuery(this).serialize();
jQuery.ajax({
url: so46065926.ajaxURL,
type: 'POST',
dataType: 'html',
data: {
action: 'research', // Remember the 'wp_ajax_research' above? This is the wp_ajax_{research} part
formData: formData,
}
})
.done(function(data) {
jQuery('.my-ajax-div').html(data);
})
.fail(function(jqXHR, textStatus, errorThrown) { // HTTP Error
console.error(errorThrown);
});
});
请记住,这只是你的目标的基础,有大量的参考文献可以帮助你。
感谢您的答案! –
你检查了[这个codex页面](https://codex.wordpress.org/AJAX_in_Plugins)吗?即使它说插件,它也适用于主题。只需将服务器端代码放入您的functions.php – Mithc