Javascript 从客户端用Ajax调用Wordpress函数
我正在用WooCommerce建立一个Wordpress网站,我还在为我的小店制作一个HTML5应用程序。我的愿望是从我的HTML5应用程序中通过Ajax调用Wordpress函数(如research),并通过商店中的产品图像获得结果。我向谷歌了解了这件事,但没什么有趣的Javascript 从客户端用Ajax调用Wordpress函数,javascript,php,jquery,ajax,wordpress,Javascript,Php,Jquery,Ajax,Wordpress,我正在用WooCommerce建立一个Wordpress网站,我还在为我的小店制作一个HTML5应用程序。我的愿望是从我的HTML5应用程序中通过Ajax调用Wordpress函数(如research),并通过商店中的产品图像获得结果。我向谷歌了解了这件事,但没什么有趣的 谢谢。首先,您必须确保可以动态获取WordPressadmin ajax.phpURL(除非您的HTML5应用程序不是WordPress商店的一部分,否则不要硬编码)。为此,请将其添加到主题的functions.php: fu
谢谢。首先,您必须确保可以动态获取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 );
} );
} );
请记住,这只是你目标的基础,有大量的参考资料可以帮助你。你检查了吗?尽管它说的是插件,但它也适用于主题。只需将服务器端代码放入函数中即可。php感谢您的回答!