Wordpress ajax 返回带有 php 开始标签的 JSON

Posted

技术标签:

【中文标题】Wordpress ajax 返回带有 php 开始标签的 JSON【英文标题】:Wordpress ajax returns JSON with php opening tag 【发布时间】:2017-04-13 01:55:16 【问题描述】:

我正在 wordpress 中创建一个 ajax 注册。我处理从 JS 发送到 php 的数据,然后使用下面的代码发回响应。

wp_send_json(array('success' => 'false', 'message' => __( 'Please select a user type.' )));

但我得到的 JSON 响应总是以 php 开始标签开头。

<?php"success":"false","message":"Please select a user type."

找不到原因。

这是我的 php 代码

<?php

if ( !is_user_logged_in() ) 
    add_action( 'init', 'auth_init' );


function auth_init() 
    wp_enqueue_script( 'user-auth-js', get_stylesheet_directory_uri() . '/assets/js/user-auth.js', array(), false, true );

    add_action( 'wp_ajax_nopriv_ajax_registration', 'ajax_registration');


add_action( 'buddyboss_after_header', 'registration_modal' );
function registration_modal() 
    if ( !is_user_logged_in() && !bp_is_register_page() ) 
        $bp = buddypress();

        if( empty( $bp->signup->step ) )
            $bp->signup->step='request-details';

        get_template_part( 'partials/content', 'registration-modal' );
    


/**
 * Ajax Registration
 */
function ajax_registration()

    check_ajax_referer( 'ajax-register-nonce', 'security' );

    $info = array();

    $info[ 'user_nicename' ]    = sanitize_user( $_POST[ 'username' ] );
    $info[ 'nickname' ]         = sanitize_user( $_POST[ 'username' ] );
    $info[ 'display_name' ]     = sanitize_user( $_POST[ 'username' ] );
    $info[ 'user_login' ]       = sanitize_user( $_POST[ 'username' ] );
    $info[ 'user_pass' ]        = sanitize_text_field( $_POST[ 'password' ] );
    $info[ 'user_email' ]       = sanitize_email( $_POST[ 'email' ] );

    // Checks if user type entered is valid
    if ( !$_POST[ 'user_type' ] ) 
        wp_send_json(array('success' => 'false', 'message' => __( 'Please select a user type.' )));
    
    elseif ( sanitize_text_field( $_POST[ 'user_type' ] ) === 'client' ) 
        $info[ 'role' ] = 'client';
    
    elseif ( sanitize_text_field( $_POST[ 'user_type' ] ) === 'vendor' ) 
        $info[ 'role' ] = 'vendor';
    
    else 
        wp_send_json(array('success' => 'false', 'message' => __( 'Invalid user type selected.' )));
    

    // Registers the user
    $user_register = wp_insert_user( $info );

    // Checks for errors returned
    if ( is_wp_error( $user_register ) ) 
        $error = $user_register->get_error_codes();

        if ( in_array( 'empty_user_login', $error ) ) 
            wp_send_json(array('success' => 'false', 'message' => __( $user_register->get_error_message( 'empty_user_login' ) )));
        
        elseif ( in_array( 'existing_user_login', $error ) ) 
            wp_send_json(array('success' => 'false', 'message' => __( 'This username you entered is already registered.' )));
        
        elseif ( in_array( 'existing_user_email', $error ) ) 
            wp_send_json(array('success' => 'false', 'message' => __( 'This email address you entered is already registered.' )));
        
    


/**
 * Log in user
 * @param  string $username Username
 * @param  string $password Password
 * @return boolean           [description]
 */
function auth_user_login( $username, $password ) 
    $info = array();
    $info[ 'user_login' ]       = $username;
    $info[ 'user_password' ]    = $password;
    $info[ 'remember' ]         = true;

    $user_signon = wp_signon( $info, false );
    if ( is_wp_error( $user_signon ) ) 
        return false;
     else 
        wp_set_current_user( $user_signon->ID );
        return true;
    

user-auth.js

$(function () 

    $( '#signup_submit' ).click(function(e) 
        e.preventDefault();
        var btn = $( this ).button( 'loading' );

        var data = 
            action: "ajax_registration",
            user_type: $( 'input[name=signup_user_type]:checked', '#signup_form' ).val(),
            username: $( '#signup_username' ).val(),
            password: $( '#signup_password' ).val(),
            email: $( '#signup_email' ).val(),
            security: $( '#registration-security' ).val()
        ;

        $.post( ajaxurl, data, function( response ) 
            console.log( response );
            btn.button( 'reset' );
         );

    );


);

【问题讨论】:

你有一个额外的&lt;?php 标签? @madalinivascu,我没有多余的&lt;?php 标签 你 100% 确定吗? 是的,我 100% 确定 请分享您的完整php代码 【参考方案1】:

第一种解决方案

在您的 php 代码中与您的注册表单或表单处理程序相关的任何地方,您是否使用过类似的东西?

<?php function xxxxxx () ?>

<p>some text </p>

<?php  ?>

如果是,则将其更改为喜欢

<?php 
function xxxxxx () 
$vriable = '<p>some text </p>';
return $vriable

第二个解决方案

wp_send_json() 处理 AJAX 调用中返回内容的所有部分。首先,它使用正确的字符集将返回内容的内容类型设置为 application/json。其次,它会在发送 JSON 结果后自动调用wp_die(),这在 WordPress 中的 AJAX 调用中是必需的。

您可以考虑将wp_send_json_success() 用于成功的请求,将wp_send_json_error() 用于错误的请求,从而遵守 WordPress 处理 AJAX 请求的标准。这些函数在数组中设置success(布尔值)和data(任何类型)键并对整个数组进行编码,从而允许您以结构化的方式轻松检查请求是否成功或出现问题。

我已经稍微修改了你的代码

<?php
if ( !is_user_logged_in() ) 


    function auth_init() 
        wp_enqueue_script( 'user-auth-js', get_stylesheet_directory_uri() . '/assets/js/user-auth.js', array(), false, true ); 
    
    add_action( 'init', 'auth_init' );


    function registration_modal() 
        if ( !is_user_logged_in() && !bp_is_register_page() ) 
            $bp = buddypress();

            if( empty( $bp->signup->step ) )
                $bp->signup->step='request-details';

            get_template_part( 'partials/content', 'registration-modal' );
        
    
    add_action( 'buddyboss_after_header', 'registration_modal' );

    /**
     * Ajax Registration
     */

    function ajax_registration()

        check_ajax_referer( 'ajax-register-nonce', 'security' );
        $info = array();

        $info[ 'user_nicename' ]    = sanitize_user( $_POST[ 'username' ] );
        $info[ 'nickname' ]         = sanitize_user( $_POST[ 'username' ] );
        $info[ 'display_name' ]     = sanitize_user( $_POST[ 'username' ] );
        $info[ 'user_login' ]       = sanitize_user( $_POST[ 'username' ] );
        $info[ 'user_pass' ]        = sanitize_text_field( $_POST[ 'password' ] );
        $info[ 'user_email' ]       = sanitize_email( $_POST[ 'email' ] );

        // Checks if user type entered is valid
        if ( !$_POST[ 'user_type' ] ) 
            wp_send_json_error(array('success' => 'false', 'message' => __( 'Please select a user type.' )));
        
        elseif ( sanitize_text_field( $_POST[ 'user_type' ] ) === 'client' ) 
            $info[ 'role' ] = 'client';
        
        elseif ( sanitize_text_field( $_POST[ 'user_type' ] ) === 'vendor' ) 
            $info[ 'role' ] = 'vendor';
        
        else 
            wp_send_json_error(array('success' => 'false', 'message' => __( 'Invalid user type selected.' )));
        

        // Registers the user
        $user_register = wp_insert_user( $info );

        // Checks for errors returned
        if ( is_wp_error( $user_register ) ) 
            $error = $user_register->get_error_codes();

            if ( in_array( 'empty_user_login', $error ) ) 
                wp_send_json_error(array('success' => 'false', 'message' => __( $user_register->get_error_message( 'empty_user_login' ) )));
            
            elseif ( in_array( 'existing_user_login', $error ) ) 
                wp_send_json_error(array('success' => 'false', 'message' => __( 'This username you entered is already registered.' )));
            
            elseif ( in_array( 'existing_user_email', $error ) ) 
                wp_send_json_error(array('success' => 'false', 'message' => __( 'This email address you entered is already registered.' )));
            
        
    
    add_action( 'wp_ajax_nopriv_ajax_registration', 'ajax_registration');
    /**
     * Log in user
     * @param  string $username Username
     * @param  string $password Password
     * @return boolean           [description]
     */
    function auth_user_login( $username, $password ) 
        $info = array();
        $info[ 'user_login' ]       = $username;
        $info[ 'user_password' ]    = $password;
        $info[ 'remember' ]         = true;

        $user_signon = wp_signon( $info, false );
        if ( is_wp_error( $user_signon ) ) 
            return false;
         else 
            wp_set_current_user( $user_signon->ID );
            return true;
        
    


【讨论】:

感谢您的回答。但仍然没有解决我的问题。我注意到所有的响应,甚至是 wordpress auth check pass json 都带有一个打开的 php 标签&lt;?php"wp-auth-check":false,"server_time":1480418708 @它在您的本地服务器中吗?还是现场服务器?能给我看看链接吗? @marccaps 我添加了另一个可能的解决方案,请检查 它在我的本地服务器上。我已经应用了您的两个解决方案,但问题仍然存在。 这是 buddypress 插件。每当我激活它时,&lt;?php 标记就会被添加到前面。仍然不知道是什么原因造成的。我已经在他们的支持下报告了这一点。感谢您的所有帮助,@Firefog!【参考方案2】:

只是为了结束这个话题。问题是functions.php文件中没有注释我在functions.php中添加以下内容后,问题就消失了。

检查这个 https://***.com/a/36939507/6417957

 <?php
/**
 * Twenty Fifteen functions and definitions
 *
 * Set up the theme and provides some helper functions, which are used in the
 * theme as custom template tags. Others are attached to action and filter
 * hooks in WordPress to change core functionality.
 *
 * When using a child theme you can override certain functions (those wrapped
 * in a function_exists() call) by defining them first in your child theme's
 * functions.php file. The child theme's functions.php file is included before
 * the parent theme's file, so the child theme functions would be used.
 *
 * @link https://codex.wordpress.org/Theme_Development
 * @link https://codex.wordpress.org/Child_Themes
 *
 * Functions that are not pluggable (not wrapped in function_exists()) are
 * instead attached to a filter or action hook.
 *
 * For more information on hooks, actions, and filters,
 * @link https://codex.wordpress.org/Plugin_API
 *
 * @package WordPress
 * @subpackage Twenty_Fifteen
 * @since Twenty Fifteen 1.0
 */

【讨论】:

是的没错,但是一般来说,出现这个问题是因为&lt;?php标签后面没有空行

以上是关于Wordpress ajax 返回带有 php 开始标签的 JSON的主要内容,如果未能解决你的问题,请参考以下文章

Ajax自定义函数在wordpress中返回0

在wordpress中返回真假的Ajax函数问题

WordPress 中的 AJAX 只返回 0

Wordpress ajax 返回 html

如何在 Wordpress 中使用 Ajax 将 Javascript 对象传递给 PHP

wordpress插件中的ajax错误