如何使用AJAX更新帖子(无插件)

时间:2014-10-29 作者:NikV

不久前发布了一篇教程,介绍了如何使用ajax通知发布/更新帖子,下面是其中的代码:

function my_post_type_xhr(){
    global $post;
    if(\'my_post_type\' === $post->post_type){
        $post_url = admin_url(\'post.php\'); #In case we\'re on post-new.php
        echo "
        <script>
            jQuery(document).ready(function($){
                //Click handler - you might have to bind this click event another way
                $(\'input#publish, input#save-post\').click(function(){
                    //Post to post.php
                    var postURL = \'$post_url\';

                    //Collate all post form data
                    var data = $(\'form#post\').serializeArray();

                    //Set a trigger for our save_post action
                    data.push({foo_doing_ajax: true});

                    //The XHR Goodness
                    $.post(postURL, data, function(response){
                        var obj = $.parseJSON(response);
                        if(obj.success)
                            alert(\'Successfully saved post!\');
                        else
                            alert(\'Something went wrong. \' + response);
                    });
                    return false;
                });
            });
        </script>";
    }
}
add_action(\'admin_head-post.php\', \'my_post_type_xhr\');
add_action(\'admin_head-post-new.php\', \'my_post_type_xhr\');
它还有第二部分:

 add_action(\'save_post\', \'save_my_post_type\');
function save_my_post_type($post_id){
    if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE) return;

    #If this is your post type
    if(\'my_post_type\' === $_POST[\'post_type\']){
        //Save any post meta here

        #We conditionally exit so we don\'t return the full wp-admin load if foo_doing_ajax is true
        if(isset($_POST[\'foo_doing_ajax\']) && $_POST[\'foo_doing_ajax\'] === true){
            header(\'Content-type: application/json\');
            #Send a response
            echo json_encode(array(\'success\' => true));
            exit;
            #You should keep this conditional to degrade gracefully for no JS
        }
    }
}
虽然此解决方案可行,但它有几个缺陷:

在该代码段中,没有弹出消息表明该帖子类型已保存。在该代码段中,您可以在离开帖子类型时发出警告,询问您是否要离开,即使帖子已更新

谢谢

1 个回复
SO网友:Jess Mann

这个问题很老了,但为了将来参考,请查看我对原始问题的回答here. 要点是:

Confirmation Dialog

警报在wp admin/js/post中生成。js和wp包括/js/autosave。js。理论上,您应该能够在$中使用以下代码行。成功后功能:

wp.autosave.initialCompareString = wp.autosave.getCompareString();
但这似乎不起作用。相反,您可以替换beforeunload函数,如下所示:

// Replaces wp.autosave.initialCompareString
var ajax_updated = false;

// Supercede the WP beforeunload function                  
$(window).unbind(\'beforeunload.edit-post\');
$(window).on( \'beforeunload.edit-post\', function() {
        var editor = typeof tinymce !== \'undefined\' && tinymce.get(\'content\');

        // Use our "ajax_updated" var instead of wp.autosave.initialCompareString
        if ( ( editor && !editor.isHidden() && editor.isDirty() ) ||
                ( wp.autosave && wp.autosave.getCompareString() != ajax_updated) ) {
                return postL10n.saveAlert; 
        }
});    
然后在$中将ajax\\u更新为正确的内容。post success功能,因此:

// Mark TinyMCE as saved
if (typeof tinyMCE !== \'undefined\') {
        for (id in tinyMCE.editors) {
                var editor = tinyMCE.get(id);
                editor.isNotDirty = true;
        }
}   
// Update the saved content for the beforeunload check
ajax_updated = wp.autosave.getCompareString();

Adding an alert message

您还询问了添加警报消息的问题。你可以用很多不同的方法。最简单、最丑陋的方法是使用javascript alert()函数,如下所示:

alert("Post saved");
就我个人而言,我更喜欢jquery notify library. 包含库后,您将分别将其放置在成功和失败函数中:

$.notify(\'Post saved\',\'success\');
$.notify(\'Something went wrong\',\'error\');

结束