AJAX returns response 0

时间:2013-12-11 作者:Christiaan

我试图使用AJAX调用获取用户配置文件值,但响应总是0。以下是我的PHP:

wp_enqueue_script( // Add JS to <head>
    \'cc-author-change-post-author\',
    plugins_url( \'assets/js/change-post-author.js\', dirname( __FILE__ ) ),
    \'jquery\'
);
wp_localize_script( // Localize script for AJAX calls
    \'cc-author-change-post-author\', // Name of script call being localized
    \'authorchange\', // AJAX object namespace, used to call values in the JS file
    array(
        \'ajaxurl\'   => admin_url( \'admin-ajax.php\' ), // URL for admin AJAX calls
        \'nonce\'     => wp_create_nonce( \'cc-author-change-author-nonce\' ) // Nonce to authenticate request
    )
);

function cc_author_change_postauthor_callback() {
    $nonce = $_POST[\'nonce\']; // Assign a local variable for nonce

    if ( ! wp_verify_nonce( $nonce, \'cc-author-change-author-nonce\' ) ) { // If the nonce doesn\'t check out, fail the request
        exit( \'Your request could not be authenticated\' ); // Error message for unauthenticated request
    }

    if ( current_user_can( \'edit_others_posts\' ) || current_user_can( \'edit_others_pages\' ) ) { // Check for proper permissions before handling request
        $author = $_POST[\'authorID\']; // Assign local variable for submitted post author

        if ( $author ) { // If an author ID was provided, get the user\'s details
            $authordata = get_userdata( $author ); // Retrieve the selected user\'s data from their profile

            $authormeta = json_encode( array( // Encode data as JSON
                \'display_name\'  => $authordata[\'display_name\'], // Display name from profile
                \'description\'   => $authordata[\'description\'] // Biographical info from profile
            ) );
        }
        else { // If no author ID was provided, send back an error message
            $authormetaerror = \'No user ID provided. Please try again.\'; // Error message to send back
            $authormeta = json_encode( array( // Encode as JSON
                \'display_name\'  => $authormetaerror,
                \'description\'   => $authormetaerror
            ) );
        }

        echo $authormeta; // Return the values retrieved from the database
    }

    exit; // End response. Required for callback to return a proper result.
} // cc_author_change_postauthor_callback()
add_action( \'wp_ajax_cc_author_change_postauthor\', \'cc_author_change_postauthor_callback\' );
下面是我的JavaScript:

jQuery( document ).ready( function( $ ) { // Don\'t execute anything until the page is loaded
    $( "#cc_author_postauthor" ).change( function() { // If the author dropdown value is changed, execute the script
        /* Data to pass to the server. Called below during $.post() */
        var data = {
            action : \'cc_author_change_postauthor\',             // Action hook for the server-side callback
            nonce : authorchange.nonce,                         // Nonce received from server to authenticate request
            authorID : $( "#cc_author_postauthor" ).val()       // author ID for retrieving profile data
        };

        /* Send request to the server and process response */
        $.post(
            authorchange.ajaxurl,                               // URL to send the request to the server
            data,                                               // Data to send to the server, stored in var data
            function( jsonString ) {                            // Script to execute upon successful response from server
                var authormeta = $.parseJSON( jsonString );     // Parse the JSON received from the server response

                $( "#cc_author_meta\\\\[0\\\\]\\\\[display_name\\\\]" ).val( authormeta.display_name ); // Change the value of the author display name to the value received from the server
                $( "#cc_author_meta\\\\[0\\\\]\\\\[description\\\\]" ).val( authormeta.description );   // Change the value of the author bio to the value received from the server
            } // function( jsonString )
        ); // $.post
    }); // $( "#cc_author_postauthor" ).change()
});
下面是表单项所在的元框:

function cc_author_metabox( $post ) {
    /* Retrieve current values if they exist */
    $cc_author_meta = get_post_meta( $post->ID, \'_cc_author_meta\', true ); // Author meta data (stored as an array)
    $postauthorid = $post->post_author; // Get the user ID of the post author

    /* If any of the values are missing from the post, retrieve them from the author\'s global profile */
    if ( !$cc_author_meta ) {       
        $postauthor = get_userdata( $postauthorid ); // Retrieve the details of the post author

        $cc_author_meta = array(); // Initialize main array
        $cc_author_meta[0] = array( // Nested array for author data
            \'display_name\'  => $postauthor->display_name, // Set display name from post author\'s data
            \'description\'   => $postauthor->description // Set bio from the post author\'s data
        );
    }

    /* Display the meta box contents */
    ?>
    <div class="cc_author_metabox">
        <p>Changes made to this information will only apply to this post, and will not be saved to the user\'s profile.</p>
        <?php
        if ( current_user_can( \'edit_others_posts\' ) || current_user_can( \'edit_others_pages\' ) ) { // Check the capabilities of the current user for sufficient privileges
            wp_dropdown_users( array(
                \'name\'          => \'cc_author_postauthor\', // Name for the form item
                \'id\'            => \'cc_author_postauthor\', // Class for the form item
                \'selected\'      => $postauthorid // Select the post\'s author to be displayed by default
            ) );
            ?>
            <noscript>
                You have JavaScript disabled. If you change the post author in the dropdown, you will need to save the post for the fields below to update. Please enable JavaScript for a better experience.
            </noscript>
            <div id="cc_author_postauthor_loading" class="cc_author_postauthor_loading"><img id="cc_author_postauthor_loading_img" class="cc_author_postauthor_loading_img" src="<?php echo plugins_url( \'assets/img/loading.gif\', dirname( __FILE__ ) ); ?>" width="20px" style="width: 20px;"></div>
            <input type="hidden" name="cc_author_currentpostauthor" value="<?php echo $postauthorid; ?>">
            <?php
        }
        ?>
        <label for="cc_author_meta[0][display_name]" class="selectit">Name</label>
        <input type="text" name="cc_author_meta[0][display_name]" id="cc_author_meta[0][display_name]" value="<?php echo esc_attr( $cc_author_meta[0][\'display_name\'] ); ?>" />

        <label for="cc_author_meta[0][description]" class="selectit">Bio</label>

        <?
        $descEditor = new ccAuthorDescEditor( $cc_author_meta[0][\'description\'], \'cc_author_meta[0][description]\' ); // Create the bio editor object
        echo $descEditor->editor(); // Display the editor
        ?>
    </div>
    <?php
}
我确信答案就在眼前,但这是我第一次使用WordPress AJAX API。我做错了什么?

你可以在网站上看到完整的插件代码its Github repository.

3 个回复
SO网友:sri

你的动作钩应该是

add_action( \'wp_ajax_cc_author_change_postauthor\', \'cc_author_change_postauthor_callback\' );
我认为,由于错误的钩子,您的回调函数永远不会被调用。

你可能也弄错了。在JS代码中,请更改您的操作

cc-author-change-postauthor

cc_author_change_postauthor

SO网友:Christiaan

我解决了这个问题。我有条件地包含了一个文件,其中只有当请求URI是用于编辑页面或帖子的URI之一时,我的PHP代码才是。因此,当通过admin ajax发出请求时,PHP代码不包括在内。php。我纠正了,现在我已经准备好了。谢谢大家的帮助!

SO网友:iFind Freelancer

而不是

exit; // End response. Required for callback to return a proper result.
使用die()wp_die() “功能。它应该是固定的。

结束

相关推荐

Include jQuery UI as a whole

是否可以将jQuery UI作为一个整体,而不是:wp_enqueue_script(\'jquery-ui-core\'); wp_enqueue_script(\'jquery-effects-core\'); // a lot of other jquery ui imports.... 我在codex中进行了搜索,找到了包含脚本的完整列表,但找不到将完整jQuery UI版本作为一个导入包含在内的方法,如:wp_enqueue_script(\'jquery-ui\');