从客户端

时间:2017-09-06 02:35:07

标签: javascript php jquery ajax wordpress

我正在使用WooCommerce构建一个Wordpress网站,我也在为我的小商店制作一个HTML5应用程序。我的愿望是通过我的HTML5应用程序中的Ajax调用Wordpress函数(例如研究),并在我的商店中获得带有图像的结果。我在谷歌上找到了它,但没有什么真正有趣的......

感谢。

1 个答案:

答案 0 :(得分:1)

首先,您必须确保可以动态获取WordPress admin-ajax.php网址(从不硬编码,除非您的 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 );
    } );
} );

请记住,这只是您的目标的基础,有大量的参考资料可以帮助您。