我正在用WooCommerce构建一个Wordpress网站,我也在为我的小商店制作一个HTML5应用程序。我的愿望是从我的HTML5应用程序中通过Ajax调用Wordpress函数(如研究),并在我的商店中获取profucts图像的结果。我在谷歌上查过,但没什么特别有趣的.
谢谢。
发布于 2017-09-06 03:36:23
首先,您必须确保可以动态地获得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 );
} );
} );记住,这只是你的目标的基础,有大量的参考资料可以帮助你。
https://stackoverflow.com/questions/46065926
复制相似问题