AJAX POST返回完整的html页面作为响应

时间:2019-06-19 作者:Eli

我知道这里经常有人问这个问题,但我找到的解决方案似乎都不适合我。

问题如下:每当我发布表单时,我都会有一个控制台日志,其中的响应是一个完整的html页面,而不是一条简单的消息。

后端脚本:

    add_action( \'admin_ajax_nopriv_email_verification_form\', \'verify_and_sanitize_email_form\' );
add_action( \'admin_ajax_email_verification_form\', \'verify_and_sanitize_email_form\' );

// Email verification callback
function verify_and_sanitize_email_form() {
    // Check referer
    check_ajax_referer( \'9pU0Pk7T01\', \'security\' );

    if(empty($_POST) || !isset($_POST[\'rguroo_email\']) || !isset($_POST[\'rguroo_email_confirmation\']) || !isset($_POST[\'rguroo_desired_action\'])) {
        echo \'There is one or more empty fields\';
        wp_die();
    }
    $sanitized_email = sanitize_email( esc_html($_POST[\'rguroo_email\'] ));
    $sanitized_email_confirmation = sanitize_email( esc_html($_POST[\'rguroo_email_confirmation\'] ));
    $desired_action = esc_html($_POST[\'rguroo_desired_action\']);

    if(!is_email( $sanitized_email ) || !is_email( $sanitized_email_confirmation )) {
        echo \'Email is not valid\';
        wp_die();
    }

    if($sanitized_email !== $sanitized_email_confirmation) {
        echo \'Emails do not match\';
        wp_die();
    }

    if($desired_action !== \'purchase\' || $desired_action !== \'renewal\' || $desired_action !== \'trial\') {
        echo \'Fatal error with radio buttons\';
        wp_die();
    }

    if(!isset($_COOKIE[\'rguroo_form_type\'])) {
        echo \'Server error\';
        wp_die();
    }

    // student email verification logic
    $form_type = $_COOKIE[\'rguroo_form_type\'];
    if($form_type === \'student\') {
        $trail = substr($sanitized_email, -4);
        if($trail !== \'.edu\') {
            echo \'Not a valid student email\';
            wp_die();
        }
        // Other university specific logic here
    }
    setcookie(\'rguroo_form_action\',$desired_action, 14 * DAY_IN_SECONDS);
    setcookie(\'rguroo_form_email\', $sanitized_email, 14 * DAY_IN_SECONDS);
    echo "success";
    wp_die();
}
前端javascript:

jQuery(document).ready(function () {
  jQuery(\'form#email-verification\').on( \'submit\', function () {
    var form_data = jQuery(this).serializeArray();
    form_data.push( { "name" : "security", "value" : ajax_info.ajax_nonce } );
    jQuery.ajax({
          url : ajax_info.ajax_url,
          type : \'post\',
          data : form_data,
          success : function( response ) {
              console.log(response);
              if(response !== \'success\') {
                jQuery(\'.error\').innerHTML = response;
              } else {
                location.reload();
              }
          },
          fail : function( err ) {
              jQuery(\'.error\').innerHTML = "Cannot contact server";
          }
      });
    return false;
  });
});
表单(用于短代码):

function output_email_verification() {
    return \'<form action="\'.esc_url( admin_url("admin-ajax.php") ).\'" method="post" id="email-verification">
                <p class="error">\'.$error.\'</p>
                <input type="radio" label="Purchase 12 months access" value="purchase" name="rguroo_desired_action" checked>Purchase 12 months access</input>
                <input type="radio" label="Renew account" name="rguroo_desired_action" value="renewal">Renew account</input>
                <input type="radio" label="Create trial account" name="rguroo_desired_action" value="trial">Create trial account</input>
                <p class="form-subtext">* indicates required field</p>
                <p>Email address*</p>
                <input type="text" name="rguroo_email" required>
                <p>Re-type email address*</p>
                <input type="text" name="rguroo_email_confirmation" required>
                <input type="hidden" name="action" value="email_verification_form">
                <input type="submit" value="Submit"> 
            </form>\';
}
我知道的事情:jQuery发送帖子(或者至少发出帖子请求)没有问题。在提交时,jQuery会发送包含所有正确参数的帖子。我也知道我没有使用不同的nonce。我尝试在回调函数周围放置error\\u logs(),但没有一个在debug中显示出来。日志这让我相信回调从未真正调用过,但我不知道为什么。此外,即使我给表单做了一个应该失败的测试,jQuery仍然认为它是成功的。

我在这张表格上浪费了一整天,感觉自己像个白痴。能不能请比我多几个脑细胞的人告诉我哪里出了问题?

非常感谢你。

5 个回复
SO网友:brothman01

在ajax请求中需要一个操作来调用php函数

url : ajax_info.ajax_url,
type : \'post\',
data : form_data,
action: email_output_verification,

SO网友:Jim

对该函数的调用是对die()PHP函数的补充。区别在于,对于典型的web请求,HTML将显示给用户

摘自here

您是否尝试使用die() 而不是wp_die()exit()?

SO网友:Paul Jones

当AJAX调用中的PHP文件名无效时,就会出现此问题。

例如:

$.post
(       
  \'ajax.phpp\',
  variables,
  [...]
这将是正确的方式:

$.post
(       
  \'ajax.php\',
  variables,
  [...]

SO网友:HK89

代码中的一些问题,如fire ajax挂钩&;短代码中的窗体操作

更改代码(&C);测验

代码如下所示

功能。php

 function enqueue_scripts() {
        // Enqueue CSS
        //wp_enqueue_style(\'wp-news-search\', plugins_url(\'/css/wp-news-search.css\', __FILE__));
        // Enqueue and localize JS
        wp_enqueue_script(\'ajax-script\', get_template_directory_uri().\'/js/wp-news-search_query.js\', array(\'jquery\'), null, true);
        wp_localize_script(\'ajax-script\', \'ajax_info\',
            array(\'ajax_url\' => admin_url(\'admin-ajax.php\'),
                \'security\' => wp_create_nonce(\'9pU0Pk7T01\'),
            ));
 }



add_action( \'wp_ajax_no_email_verification_form\', \'verify_and_sanitize_email_form\' );
add_action( \'wp_ajax_email_verification_form\', \'verify_and_sanitize_email_form\' );

// Email verification callback
function verify_and_sanitize_email_form() {
    // heck referer
   check_ajax_referer( \'9pU0Pk7T01\', \'security\' );


  //  echo "string";
   parse_str($_POST[\'data\'], $data);
    

    if(empty($_POST) || !isset($data[\'rguroo_email\']) || !isset($data[\'rguroo_email_confirmation\']) || !isset($data[\'rguroo_desired_action\'])) {
        echo \'There is one or more empty fields\';
        wp_die();
    }
    $sanitized_email = sanitize_email( esc_html($data[\'rguroo_email\'] ));
    $sanitized_email_confirmation = sanitize_email( esc_html($data[\'rguroo_email_confirmation\'] ));
    $desired_action = esc_html($data[\'rguroo_desired_action\']);

    if(!is_email( $sanitized_email ) || !is_email( $sanitized_email_confirmation )) {
        echo \'Email is not valid\';
        wp_die();
    }

    if($sanitized_email !== $sanitized_email_confirmation) {
        echo \'Emails do not match\';
        wp_die();
    }

    if($desired_action !== \'purchase\' || $desired_action !== \'renewal\' || $desired_action !== \'trial\') {
        echo \'Fatal error with radio buttons\';
        wp_die();
    }

    if(!isset($_COOKIE[\'rguroo_form_type\'])) {
        echo \'Server error\';
        wp_die();
    }

    // student email verification logic
    $form_type = $_COOKIE[\'rguroo_form_type\'];
    if($form_type === \'student\') {
        $trail = substr($sanitized_email, -4);
        if($trail !== \'.edu\') {
            echo \'Not a valid student email\';
            wp_die();
        }
        // Other university specific logic here
    }
    setcookie(\'rguroo_form_action\',$desired_action, 14 * DAY_IN_SECONDS);
    setcookie(\'rguroo_form_email\', $sanitized_email, 14 * DAY_IN_SECONDS);
    echo "success";
    wp_die();
}

add_shortcode(\'wp_news_search\',\'wp_news_search_form\');
 function wp_news_search_form() {
    return \'<form id="email-verification">
            <p class="error">\'.$error.\'</p>
            <input type="radio" label="Purchase 12 months access" value="purchase" name="rguroo_desired_action" checked>Purchase 12 months access</input>
            <input type="radio" label="Renew account" name="rguroo_desired_action" value="renewal">Renew account</input>
            <input type="radio" label="Create trial account" name="rguroo_desired_action" value="trial">Create trial account</input>
            <p class="form-subtext">* indicates required field</p>
            <p>Email address*</p>
            <input type="text" name="rguroo_email" required>
            <p>Re-type email address*</p>
            <input type="text" name="rguroo_email_confirmation" required>
            <input type="hidden" name="action" value="email_verification_form">
            <input type="submit" value="Submit"> 
        </form>\';
    }
Js公司

  jQuery(document).ready(function () {
  jQuery(\'#email-verification\').submit(function (event) {
     event.preventDefault();
    var form_data = jQuery(this).serialize();
    jQuery.ajax({
          url : ajax_info.ajax_url,
          type : \'post\',
          data: {
              action: \'email_verification_form\',
              data: form_data,
              security: ajax_info.security
            },
          success : function( response ) {
              console.log(response);
              if(response !== \'success\') {
                jQuery(\'p.error\').html(response);
              } else {
                location.reload();
              }
          },
          fail : function( err ) {
              jQuery(\'.error\').innerHTML = "Cannot contact server";
          }
      });
    return false;
  });
});

SO网友:Drashti Rajpura

这可能有用。从响应中按类名找到您的div,并获取它的innerhtml。

success : function( response ) {
              var error = $(response).find(\'.error-div\')[0].innerHTML;
              if(response !== \'success\') {
                jQuery(\'.error\').innerHTML = error;
              }