WordPress的admin-ajax.php加载失败

时间:2018-10-18 10:35:51

标签: javascript php wordpress woocommerce

我正在为我的练习开发一个压词插件,并在其中通过获取一些信息来注册客户。

enter image description here

is_user_logged_in()返回false,然后我想获取脚本

function theme_enqueue_scripts() {
    if ( ! is_user_logged_in()){
        wp_enqueue_script( 'frontend-ajax', admin_url( 'admin-ajax.php' ));
        wp_localize_script( 'frontend-ajax', 'frontend_ajax_object',admin_url( 'admin-ajax.php' ));
    }
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );
add_action( 'wp_ajax_PHPSidefunction', 'PHPSidefunction' );
add_action( 'wp_ajax_nopriv_PHPSidefunctionNopriv', 'PHPSidefunctionNopriv' );

和下面来自Ajax调用代码的操作

$('#submitbutton').click(function() {

var $inputemail=document.getElementById('inputemail').value;
var $inputname=document.getElementById('inputname').value;
var $inputlastname=document.getElementById('inputlastname').value;
var $inputpassword=document.getElementById('inputpassword').value;
console.log($inputemail+$inputname+$inputlastname+$inputpassword);
console.log("<?php echo get_home_url(); ?>/wp-admin/admin-ajax.php");
$.ajax({
    url:frontend_ajax_object, 
    type: "POST",
    dataType: "Text",
    data: {
        action: "PHPSidefunctionNopriv",
        inputemail: $inputemail,
        inputname:$inputname,
        inputlastname:$inputlastname,
        inputpassword:$inputpassword
    },
    success: function (response) {
        console.log(response);
    }
    error: function(errortype,textStatus,errorThrown){
        console.log(errortype);
        console.log(textStatus);
        console.log(errorThrown);
    }
});
});

和回调函数在这里

function PHPSidefunctionNopriv(){
//echo 'i am phpside function nopriv';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if($_POST['action'] == 'PHPSidefunction'){
        $email= $_POST['inputemail'];
        $password=$_POST['inputpassword'];
        $userid=wc_create_new_customer($email,$email,$password);
        echo $userid;
        wp_die();
    }
}
}

但是在排队脚本时出现错误

enter image description here

等待帮助,谢谢。

1 个答案:

答案 0 :(得分:2)

您正尝试将PHP脚本加载为javascript文件。这是完全错误的。

function theme_enqueue_scripts() {
    wp_localize_script( 'frontend-ajax', 'frontend_ajax_object',admin_url( 'admin-ajax.php' ));
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );
add_action( 'wp_ajax_PHPSidefunction', 'PHPSidefunction' );
add_action( 'wp_ajax_nopriv_PHPSidefunctionNopriv', 'PHPSidefunctionNopriv' );

用户是否登录,没关系。对于WP_AJAX,Ajax网址将始终为admin_url('admin-ajax.php')