繁体   English   中英

使用 AJAX 和 PHP 提交表单,无需重新加载页面

[英]Submit form with AJAX and PHP without page reload

我的wordpress项目中有“添加到收藏夹”功能,我正在使用<form>提交该功能。 每次我点击添加到收藏按钮时它都会工作,但页面总是重新加载,这很烦人,所以我决定使用 AJAX,但我无法将它与我的 PHP 文件连接。

这是 PHP 文件,我在其中为该功能编写了 function

if (! function_exists('favorite_button_icon')) {

    function favorite_button_icon() {
        echo apply_filters( 'favorite_button_icon', get_the_favorite_button_icon() );
    }
}

if (! function_exists('get_the_favorite_button_icon')) {

    function get_the_favorite_button_icon() {

        $output = '';
        $action = $currentPath; // window.location.href
        $name   = is_favorite() ? 'remove_favorite' : 'add_favorite';
        $class  = 'favorite-button-pro' . ( is_favorite() ? ' favorite' : '' );
        $icon = is_favorite() ? 'Added' : 'Add';

        $output .= '<form method="post" id="favorite_user_post" 
                     class="favorite_user_post" action="'. $action .'">';
        $output .= '<button id="submit-favorite" type="submit" name="'. $name .'" 
                     value="'. get_the_ID() .'" class="'. $class .'">';
        $output .= $icon;
        $output .= '</button></form>';
        
        return apply_filters( 'get_the_favorite_button_icon', $output );
    }
} 

我只是在 html 中调用 function

<div class="add-to-favorites-option" > 
      <?php favorite_button_icon() ?>
</div>

上面的一切都有效,但正如我所说,页面正在重新加载。

这是我尝试使用 AJAX

jQuery('#favorite_user_post').submit(function (e) {
    e.preventDefault();
    var form = jQuery(this);
    var url = form.attr('action');
    jQuery.ajax({
        type: 'POST',
        url: url,
        data: form.serialize(),
        success: function (data) {
            console.log(data);
        },
        error: function () {
            console.log('Fail');
        },
    });
});

我在提交时绝对没有火,我错过了什么吗?

您需要使用wp_ajax_挂钩:https://developer.wordpress.org/reference/hooks/wp_ajax_action/

下面的简单示例:

你 PHP 代码来处理 ajax 请求:

add_action( 'wp_ajax_my_action', 'my_action' );

function my_action() {
    // code that captures your ajax POST request

    wp_die(); // this is required to terminate immediately and return a proper response
}

您的 Ajax 调用:

jQuery('#favorite_user_post').submit(function (e) {
    e.preventDefault();
    var form = jQuery(this);
    // note the added "my_action" to tell the server what function to fire (my be a better way to append this to your form data)
    var url = form.attr('action') + "&=my_action";
    jQuery.ajax({
        type: 'POST',
        url: url,
        data: form.serialize(),
        success: function (data) {
            console.log(data);
        },
        error: function () {
            console.log('Fail');
        },
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM