Full-AJAX主题:从WordPress定制模板构建JSON对象时出现parseJSON错误

时间:2015-05-30 作者:JetXS

为了对我的新作品集进行全面的ajax导航,我在网上阅读了一些不同的博客,其中提到使用JSON构建模板会更容易,以便以我想要的方式处理数据。

这不是常规程序(使用WP\\U Ajax…等)并且花了一天的时间浏览互联网。。。没有回答。这是一个非常SEO友好的技术,也可以访问(如果javascript没有激活,网站仍然可以工作…等等)。我这样做是为了确保你们理解为什么我要使用这个程序而不是更常规的程序。。。

受这些(法语)文章的启发:http://boiteaweb.fr/la-navigation-avec-ajax-7743.htmlhttp://www.seomix.fr/ajax-wordpress/

我开始按照建议的步骤进行调整,使之符合我的主题和想法。

简单总结一下:重要提示:它没有使用wp-ajax或admin-ajax技术,而是使用了另一种ajax模板slug。在链接上的AJAX请求期间,我将发送“MDXMLHTTPRequest”。

function perform_ajax_request( url ) {
        $.ajax({
            url    : url,
            type   : \'POST\',
            headers: {
                \'X-Requested-With\':\'MDXMLHttpRequest\'
            }
        }).done( function( data ) {
            var data = $.parseJSON( data );
            switch_content( current_template, data );
        }).error( function() {
            // Error
            alert( \'Unable to update the content, an error occured.\' );
        });
    }
通过以下功能,Wordpress将了解到正在发出AJAX请求,并将要求返回正确的模板(收缩的内容模板),即显示所有帖子的页面中的帖子内容。

add_filter( \'template_include\', \'md_template_include\' );  
function md_template_include( $template ) {  
    if( isset( $_SERVER[\'HTTP_X_REQUESTED_WITH\'] ) && $_SERVER[\'HTTP_X_REQUESTED_WITH\']== \'MDXMLHttpRequest\' ):  
        $pre = dirname( $template );  
        $suf = basename( $template );  
        $_template = $pre . \'/ajax-\' . $suf;  
        if( !file_exists( $_template ) )  
            $_template = $template;  
        $template = $_template;  
    endif;  
    return $template;  
}  
我认为这部分很容易理解。。。它在运行时返回带前缀的ajax模板。php接收标题。现在,我们必须构建模板,即ajax单个项目。php文件。

我试图让服务器返回一个JSON数组,以便更容易使用jQuery进行操作并在模板之间进行切换。

然而,我编写的当前代码(见下文注释)返回了一个错误,这是一个损坏的JSON数组的典型错误。因为这是我第一次尝试JSON。。我不确定我是忘了什么还是做错了什么。。。

<?php

$o = array();

$o[ \'title\' ]      = wp_title( \'|\', true, \'right\' ); //used to update the title of the browser window
$o[ \'type\' ]       = \'single-project\'; //type of the template

//The Localize script, is that ok here ?
wp_localize_script(\'my-ajax-request\', \'current_template\', array(\'the_current_template\' => basename(get_page_template())));

//ob_start();
$article = \'<div id="container" class="content-area project-content">\';
$article .=     \'<main id="main" class="site-main" role="main">\';

                 // I couldn\'t make this part work with JSON... That\'s why I rewrote the whole thing instead of loading a template part
                /*while (have_posts() ) : the_post();
                    if ( $overridden_template = locate_template( \'content-single-project.php\' ) ) {
                    // locate_template() returns path to file
                    // if either the child theme or the parent theme have overridden the template
                    load_template( $overridden_template );
                } else {
                    // If neither the child nor parent theme have overridden the template,
                    // we load the template from the \'templates\' sub-directory of the directory this file is in
                    load_template( dirname( __FILE__ ) . \'/template-parts/content-single-project.php\' );
                }
                endwhile;*/

                while (have_posts()) : the_post();

$article .=                     \'<article id="post-\'.the_ID().\'"\'.post_class().\'>\';

$article .=                         $image0 = wp_get_attachment_image_src(get_field(\'project_hero\'), \'full\');
$article .=                         \'<img class="project-hero" src="\'.$image0[0].\'" alt="\'.get_the_title(get_field(\'project_hero\')).\'" />\';

$article .=                         \'<section class="project-head entry-header">\';
$article .=                             \'<div class="clearfix">\';
$article .=                                 \'<h3 class="project-title entry-title">\';
$article .=                                     the_title();
$article .=                     \'</h3>\';
$article .=                                 \'<ul class="project-infos clearfix entry-meta">\';

                                if ( has_term(\'frontend\', \'projectcat\')) {
$article .=                                     \'<li><i class="fa fa-desktop"></i><span>Frontend</span></li>\';
                                }
                                else if ( has_term(\'design\', \'projectcat\')) {
$article .=                                     \'<li><i class="fa fa-pencil"></i><span>Design</span></li>\';
                                }
                                else if ( has_term(\'application\', \'projectcat\')) {
$article .=                                     \'<li><i class="fa fa-code"></i><span>Application</span></li>\';
                                }
                                else {
$article .=                                     \'<li><span><i class="fa fa-question"></i>Category not specified</span></li>\';
                                }

$article .=                                     \'<li><i class="fa fa-calendar"></i><span>\'.the_field(\'project_year\').\'</span></li>\';
$article .=                                     \'<li><i class="fa fa-users"></i><span>\'.the_field(\'project_client\').\'</span></li>\';
$article .=                                 \'</ul>\';
$article .=                             \'</div>\';
$article .=                             \'<div class="project-intro entry-content">\';
$article .=                                 the_content();
$article .=                             \'</div>\';
$article .=                         \'</section>\';
$article .=                         \'<section class="project-body entry-content">\';
$article .=                             \'<h4 class="project-subtitle">\'.the_field(\'project_image_section_1_title\').\'</h4>\';
                            $image1 = wp_get_attachment_image_src(get_field(\'project_image_section_1_images\'), \'full\');
$article .=                             \'<img src="\'.$image1[0].\'" alt="\'.get_the_title(get_field(\'project_image_section_1_images\')).\'" />\';
$article .=                             \'<h4 class="project-subtitle">\'.the_field(\'project_image_section_2_title\').\'</h4>\';
                            $image2 = wp_get_attachment_image_src(get_field(\'project_image_section_2_images\'), \'full\');
$article .=                             \'<img src="\'.$image2[0].\'" alt="\'.get_the_title(get_field(\'project_image_section_2_images\')).\'" />\';
$article .=                             \'<h4 class="project-subtitle">\'.the_field(\'project_image_section_3_title\').\'</h4>\';
                            $image3 = wp_get_attachment_image_src(get_field(\'project_image_section_3_images\'), \'full\');
$article .=                             \'<img src="\'.$image3[0].\'" alt="\'.get_the_title(get_field(\'project_image_section_3_images\')).\'" />\';
$article .=                         \'</section>\';
$article .=                     \'</article><!-- #post-## -->\';

                endwhile;


$article .=     \'</main><!-- #main -->\';
$article .= \'</div><!-- #primary -->\';

$o[\'article\']= $article;
//$o = ob_get_clean();

echo json_encode($o);
exit();
我认为它几乎可以工作了,我几乎可以看到光明,我使用FireBug网络检查器得到的输出(标题对象为null??)表明有很多内容没有放入JSON数组(奇怪!)这就是我无法理解的:

Alstom Blue Book | Michel Didier1793class="post-1793 project type-project status-publish has-post-thumbnail
 hentry projectcat-frontend"Alstom Blue Book2014Web Relief<p>Lorem ipsum dolor sit amet, consectetur
 adipiscing elit. Praesent magna elit, lobortis id elementum in, vestibulum vitae tortor. Proin molestie
 purus sit amet rhoncus pharetra. Nulla feugiat orci nec mattis mollis. Integer id lorem imperdiet, egestas
 nunc ac, efficitur lectus. Aenean nec ullamcorper est. Duis non urna mi. Cras dictum pharetra justo
, ac tristique augue cursus id. Maecenas sollicitudin orci ac lectus laoreet suscipit. Maecenas bibendum
 egestas justo, id consectetur lectus pharetra id. Nulla finibus eu nunc sit amet bibendum. Aliquam erat
 volutpat.</p>
HomeArticleMapping{"title":null,"type":"single-project","article":"<div id=\\"container\\" class=\\"content-area
 project-content\\"><main id=\\"main\\" class=\\"site-main\\" role=\\"main\\"><article id=\\"post-\\">Array<img
 class=\\"project-hero\\" src=\\"http:\\/\\/localhost:8888\\/portfolio\\/wp-content\\/uploads\\/2015\\/05\\/alstom_hero
.png\\" alt=\\"alstom_hero\\" \\/><section class=\\"project-head entry-header\\"><div class=\\"clearfix\\"><h3
 class=\\"project-title entry-title\\"><\\/h3><ul class=\\"project-infos clearfix entry-meta\\"><li><i class
=\\"fa fa-desktop\\"><\\/i><span>Frontend<\\/span><\\/li><li><i class=\\"fa fa-calendar\\"><\\/i><span><\\/span
><\\/li><li><i class=\\"fa fa-users\\"><\\/i><span><\\/span><\\/li><\\/ul><\\/div><div class=\\"project-intro
 entry-content\\"><\\/div><\\/section><section class=\\"project-body entry-content\\"><h4 class=\\"project-subtitle
\\"><\\/h4><img src=\\"http:\\/\\/localhost:8888\\/portfolio\\/wp-content\\/uploads\\/2015\\/05\\/alstom_01.png
\\" alt=\\"alstom_01\\" \\/><h4 class=\\"project-subtitle\\"><\\/h4><img src=\\"http:\\/\\/localhost:8888\\/portfolio
\\/wp-content\\/uploads\\/2015\\/05\\/alstom_02.png\\" alt=\\"alstom_02\\" \\/><h4 class=\\"project-subtitle\\"
><\\/h4><img src=\\"http:\\/\\/localhost:8888\\/portfolio\\/wp-content\\/uploads\\/2015\\/05\\/alstom_03.png\\"
 alt=\\"alstom_03\\" \\/><\\/section><\\/article><!-- #post-## --><\\/main><!-- #main --><\\/div><!-- #primary
 -->"}
感谢您的时间、帮助和阅读,

我努力做到真正完整,希望我的英语不会对所有这些细节造成任何麻烦。。。

注意:原文章的作者建议使用wp\\u localize\\u script()跟踪我们当前所在的模板(并在不同的情况下进行切换,从列表切换到单个…等等),我不确定这部分,如果我将wp\\u localize\\u脚本放在合适的位置。。。如果你们理解这个原则,知道它是否好,请告诉我:)

EDIT问题似乎来自一些Wordpress编码。

我在哪里

$article .=                                                     \'<div class="project-intro entry-content">\';
$article .=                                                             the_content();
$article .=                                                     \'</div>\';
如果我替换为

        $article .= \'<div class="project-intro entry-content">\'.get_the_content().\'</div>\';
帖子内容正确地放置在JSON字符串中,而不是放在JSON字符串之外。我想是吧the_content()正在破坏JSON字符串the_ID(), wp_title().. 等等。有什么建议吗?

1 个回复
SO网友:JetXS

替换所有特定the_content() 功能,或the_ID... 由getters等效的etc似乎解决了这个问题。解决方案如下:

<?php

$o = array();

$o[ \'title\' ] = wp_title( \'|\', false, \'right\' );
$o[ \'type\' ] = \'single-project\';

//ob_start();
$article = \'<div id="container" class="content-area project-content">\';
    $article .= \'<main id="main" class="site-main" role="main">\';

        while (have_posts()) : the_post();

        $article .= \'<article id="post-\'.get_the_ID().\'"\'.get_post_class().\'>\';

            $article .= $image0 = wp_get_attachment_image_src(get_field(\'project_hero\'), \'full\');
            $article .= \'<img class="project-hero" src="\'.$image0[0].\'" alt="\'.get_the_title(get_field(\'project_hero\')).\'" />\';

            $article .= \'<section class="project-head entry-header">\';
                $article .= \'<div class="clearfix">\';
                    $article .= \'<h3 class="project-title entry-title">\';
                        $article .= get_the_title();
                    $article .= \'</h3>\';
                    $article .= \'<ul class="project-infos clearfix entry-meta">\';

                        if ( has_term(\'frontend\', \'projectcat\')) {
                            $article .= \'<li><i class="fa fa-desktop"></i><span>Frontend</span></li>\';
                        }
                        else if ( has_term(\'design\', \'projectcat\')) {
                            $article .= \'<li><i class="fa fa-pencil"></i><span>Design</span></li>\';
                        }
                        else if ( has_term(\'application\', \'projectcat\')) {
                            $article .= \'<li><i class="fa fa-code"></i><span>Application</span></li>\';
                        }
                        else {
                            $article .= \'<li><span><i class="fa fa-question"></i>Category not specified</span></li>\';
                        }

                        $article .= \'<li><i class="fa fa-calendar"></i><span>\'.get_field(\'project_year\').\'</span></li>\';
                        $article .= \'<li><i class="fa fa-users"></i><span>\'.get_field(\'project_client\').\'</span></li>\';
                    $article .= \'</ul>\';
                $article .= \'</div>\';
                $article .= \'<div class="project-intro entry-content">\'.get_the_content().\'</div>\';
            $article .= \'</section>\';
            $article .= \'<section class="project-body entry-content">\';
                $article .= \'<h4 class="project-subtitle">\'.get_field(\'project_image_section_1_title\').\'</h4>\';
                $image1 = wp_get_attachment_image_src(get_field(\'project_image_section_1_images\'), \'full\');
                $article .= \'<img src="\'.$image1[0].\'" alt="\'.get_the_title(get_field(\'project_image_section_1_images\')).\'" />\';
                $article .= \'<h4 class="project-subtitle">\'.get_field(\'project_image_section_2_title\').\'</h4>\';
                $image2 = wp_get_attachment_image_src(get_field(\'project_image_section_2_images\'), \'full\');
                $article .= \'<img src="\'.$image2[0].\'" alt="\'.get_the_title(get_field(\'project_image_section_2_images\')).\'" />\';
                $article .= \'<h4 class="project-subtitle">\'.get_field(\'project_image_section_3_title\').\'</h4>\';
                $image3 = wp_get_attachment_image_src(get_field(\'project_image_section_3_images\'), \'full\');
                $article .= \'<img src="\'.$image3[0].\'" alt="\'.get_the_title(get_field(\'project_image_section_3_images\')).\'" />\';
            $article .= \'</section>\';
        $article .= \'</article><!-- #post-## -->\';

    endwhile;


$article .=\'</main><!-- #main -->\';
$article .=\'</div><!-- #primary -->\';

$o[\'article\']= $article;
//$o = ob_get_clean();

echo json_encode($o);
exit();

结束

相关推荐

JSON API不返回所有元数据

我正在使用此插件https://wordpress.org/plugins/json-api/要创建新条目,请将所有wp\\U Posteta customfield表正确保存在数据库中,但在运行api/get_post/?post_type=job_listing&post_id=542结果不完整,只给出了一些自定义字段。示例:meta_key meta_value _company_phone 89998983