【问题标题】:Calling Wordpress functions with Ajax from client side从客户端使用 Ajax 调用 Wordpress 函数
【发布时间】:2018-02-14 09:30:30
【问题描述】:

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

谢谢。

【问题讨论】:

  • 你检查this codex page了吗?即使它说插件,它也适用于主题。只需将服务器端代码放入您的functions.php

标签: javascript php jquery ajax wordpress


【解决方案1】:

首先,您必须确保您可以动态获取 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 );
    } );
} );

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

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 2020-08-18
  • 2016-06-27
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 2011-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多