如何在Wordpress中使用Ajax? [英] How to use ajax in Wordpress?

查看:112
本文介绍了如何在Wordpress中使用Ajax?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在wordpress中使用ajax.我该怎么做?我已经在这里附加了我的代码.但这对我不起作用.这是我的wordpress动作和技巧.

I want to use ajax in wordpress. How can I do it? I have attached my code here. But this is not working for me. Here it is my wordpress action and hook.

function ajax_enqueuescripts() {
    wp_enqueue_script('ajaxloadpost', get_template_directory_uri().'/js/my-ajax.js', array('jquery'));
    wp_localize_script( 'ajaxloadpost', 'ajax_postajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

add_action('wp_enqueue_scripts', ajax_enqueuescripts);

add_action('wp_ajax_nopriv_ajax_ajaxhandler', 'my_action_callback' );
add_action('wp_ajax_ajax_ajaxhandler', 'my_action_callback' );

function my_action_callback(){  
    //echo "Df";print_r($_POST);die;
}

这是我的js代码

jQuery(document).ready(function(){
 jQuery('#event-form').submit( function () {

    var email = jQuery('#event_name').val();
jQuery.ajax({
        type: 'POST',
        url: ajax_postajax.ajaxurl,
        data: {
            action: 'ajax_ajaxhandler',
        email : email   
        },
        success: function() {
            alert(email);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Fd");
        }
    });

    return false;
  });
});

推荐答案

在成功的ajax函数中发出警报的值必须来自您的php函数,因此您将具有以下内容:

The value that you alert in your success ajax function must come from your php function so you would have something like this:

PHP

function my_action_callback(){  
    echo $_POST['email']; die();
}

JavaScript

jQuery.ajax({
        type: 'POST',
        url: ajax_postajax.ajaxurl,
        data: {
            action: 'ajax_ajaxhandler',
        email : email   
        },
        success: function(data) {
            alert(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Fd");
        }
    });

在您的情况下,JavaScript中的数据将等于您在php函数中回显的任何数据.

in your case data in javascript will be equal to anything that you echo out in your php function.

在这种情况下,您可以通过对数组进行编码来将json对象发送到javascript

You can send json objects to javascript by encoding arrays in which case you would have

PHP

function my_action_callback(){  


    echo json_encode('email' => $_POST['email']));

die();
}

JavaScript

Javascript

jQuery.ajax({
        type: 'POST',
        url: ajax_postajax.ajaxurl,
        data: {
            action: 'ajax_ajaxhandler',
        email : email   
        },
        success: function(data) {
            alert(data.email);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Fd");
        }
    });

我仅向您提供了代码中需要替换的位置的示例,其余的看起来还不错.

I only gave you example of the places in your code that needed to be replaced, the rest seems alright.

这篇关于如何在Wordpress中使用Ajax?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆