为什么Wordpress AJAX请求会返回整个HTML页面而不是json结果?

时间:2015-07-03 11:12:58

标签: ajax wordpress

如果用户提供的电子邮件已经在数据库中,我目前正在尝试检查html表单。因此,如果get_user_by函数有效,我的PHP文件必须返回true。

我已经遵循了所有 Wordpress指南 AJAX请求,并测试了两种AJAX方法( jQuery和vanilla JS )。

jQuery方法在错误回调中完成(xhr.responseText对应于整个当前HTML页面),而vanilla JS方法在成功回调中返回但总是返回0.

首先,我注册我的ajax js文件并将其本地化以获得良好的admin-ajax.php url。然后我得到了我的自定义AJAX钩子:wp_ajax_nopriv_get_user_by_email其中get_user_by_email是请求的动作数据。

<?php 
/* Security access : Hacker can't access php files here */
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
   wp_register_script( "ajax_user_call", MY_PLUGIN_URL.'js/ajax_user_call.js', array('jquery'));
   wp_localize_script( 'ajax_user_call', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        

   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'ajax_user_call' );
}

if ( is_admin() ) {
    add_action( 'wp_ajax_nopriv_get_user_by_email', 'my_plugin_ajax_get_user_by_email' );

    function my_plugin_ajax_get_user_by_email() {
        my_plugin_log_me("Is there somebody ?");
        // get the mail parameter from URL
        $mail = $_REQUEST["mail"];
        if ( isset($_REQUEST["mail"]) && !empty($_REQUEST["mail"]) ) {
            $user = get_user_by('email', $_REQUEST["mail"]);
            if ($user == false) {
                echo -2;
                wp_die();
            }
            else {
                $response['first_name'] = $user->first_name;
                $response['last_name'] = $user->last_name;

                wp_send_json($response);
            }
        }
        else {
            echo -3;
            wp_die();
        }
    }

} ?>

现在我把ajax_user_call.js:

jQuery(document).ready( function() {
  jQuery("#identificationEmailInput").blur( function() {
    jQuery.ajax({
       type: "post",
       dataType: "json",
       cache: false,
       url: myAjax.ajaxurl,
       data: { action: "get_user_by_email", mail: this.value },
       success: function(response, statut) {
          if(response == 0) {
            console.log("Veuillez rentrer une adresse mail du Club Savignac");
          }
          else {
            user = response;
            console.log("USER : " + user);
          }
       },
       error: function(xhr, textStatus, errorThrown) {
          console.log("AJAX Request failed");
          console.log(textStatus);
          console.log(errorThrown);
          console.log(xhr.responseText);
       }
    });
  });
})

jQuery(“#identificationEmailInput”)。value返回一个好的电子邮件字符串。 url参数myAjax.ajaxurl返回良好路径:“http://mysite.fr/wp-admin/admin-ajax.php”。

我还尝试对这些参数进行硬编码:

jQuery.post(
  "../wp-admin/admin-ajax.php",
  {
    action: 'get_user_by_email',
    mail: 'myprivate@mail.com'
  },
  function( response ) {
    console.log( response );
  }
);

然后,我也试着和Vanilla JS一样:

  var getJSON = function(url, param1, param2, successHandler, errorHandler) {
    var xhr = new XMLHttpRequest();
    xhr.open('post', url, true);
    var params = "action=" + param1 + "&mail=" + param2;
    console.log(params);
    xhr.responseType = 'json';

    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        successHandler && successHandler(xhr.response);
      } else {
        errorHandler && errorHandler(status);
      }
    };
    xhr.send(params);
  };

  jQuery(document).ready( function() {
    jQuery("#identificationEmailInput").blur( function() {

      getJSON(myAjax.ajaxurl, 'get_user_by_email', jQuery("#identificationEmailInput").val(), function(data) {
          console.log('user object: ' + data);
        }, function(status) {
          console.log('Something went wrong.');
      });
    });
  })

但数据值始终返回0.

有人对这个棘手的问题有所了解吗?最令人惊讶的是它在两天前工作了,现在它已经不存在了,而我没有做任何改动。

1 个答案:

答案 0 :(得分:0)

添加这个你的插件php文件并检查它。

 add_action('wp_ajax_nopriv_get_user_by_email', 'get_user_by_email');
    add_action('wp_ajax_get_user_by_email', 'get_user_by_email');

    function get_user_by_email(){

    $user_email  = $_POST['email'];
    //do some thing with the email

    die();
    }
相关问题