首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从客户端用Ajax调用Wordpress函数

从客户端用Ajax调用Wordpress函数
EN

Stack Overflow用户
提问于 2017-09-06 02:35:07
回答 1查看 1.4K关注 0票数 1

我正在用WooCommerce构建一个Wordpress网站,我也在为我的小商店制作一个HTML5应用程序。我的愿望是从我的HTML5应用程序中通过Ajax调用Wordpress函数(如研究),并在我的商店中获取profucts图像的结果。我在谷歌上查过,但没什么特别有趣的.

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-06 03:36:23

首先,您必须确保可以动态地获得WordPress admin-ajax.php URL (永远不要硬编码,除非您的HTML5应用程序不是WordPress商店的一部分)。为此,请将其添加到主题的functions.php

代码语言:javascript
复制
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

代码语言:javascript
复制
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' );

然后,您就可以构建客户端脚本了。可能是这样的:

代码语言:javascript
复制
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 );
    } );
} );

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46065926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档