代码之家  ›  专栏  ›  技术社区  ›  J. Doe

WordPress用json\u编码从php向js发帖,并将ID发到div

  •  0
  • J. Doe  · 技术社区  · 8 年前

    我使用以下几行代码将帖子作为一个数组来获取,然后通过将带有json\u encode的帖子转换为json将其发送回js,js会要求这样做

    function get_feedback() {
        if(isset($_POST['postId'])){
            $postId = $_POST['postId'];
        } 
        $cToken = get_post_meta($postId, 'cToken', true);
        $posts = get_posts(
            array(
            'numberposts' => -1,
            'post_type' => 'post',
            'category' => 'Feedback',
            'meta_key' => 'cToken',
            'meta_value' => $cToken
            )
        );
    
        echo json_encode($posts);
        wp_die();
    }
    

    然后,我尝试将所有帖子id的列表发布到WordPressPage上的一个div中,代码如下

    function getFeedback(postId){
        $(".show_company").hide();
        $(".show_feedback").show();
        $.ajax({
            type: "POST",
            url: ajax_object.ajax_url,
            data:{
            action:'get_feedback', 
            postId: postId,
            },
            success:function(response) {
            $("#result").html(response);
            alert(response[0]);
    
    
            }
        });
    }
    

    但这只是未定义的消息。

    从php传递到js的对象如下图所示:

    [{"ID":387,"post_author":"9","post_date":"2018-05-17 23:06:35","post_date_gmt":"2018-05-17 23:06:35","post_content":"","post_title":"jitz - grad - 0106","post_excerpt":"","post_status":"publish","comment_status":"open","ping_status":"open","post_password":"","post_name":"jitz-grad-0106","to_ping":"","pinged":"","post_modified":"2018-05-17 23:06:35","post_modified_gmt":"2018-05-17 23:06:35","post_content_filtered":"","post_parent":0,"guid":"http:\/\/localhost\/wp\/jitz-grad-0106\/","menu_order":0,"post_type":"post","post_mime_type":"","comment_count":"0","filter":"raw"},{"ID":386,"post_author":"9","post_date":"2018-05-17 23:06:16","post_date_gmt":"2018-05-17 23:06:16","post_content":"","post_title":"hergott - 0001 - 4","post_excerpt":"","post_status":"publish","comment_status":"open","ping_status":"open","post_password":"","post_name":"hergott-0001-4","to_ping":"","pinged":"","post_modified":"2018-05-17 23:06:16","post_modified_gmt":"2018-05-17 23:06:16","post_content_filtered":"","post_parent":0,"guid":"http:\/\/localhost\/wp\/hergott-0001-4\/","menu_order":0,"post_type":"post","post_mime_type":"","comment_count":"0","filter":"raw"}]
    

    所以它基本上是一个包含两个对象的对象,这两个对象都是post。我如何在这里处理帖子的属性?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Aaron Lamar    8 年前

    看起来您想将响应解析为JSON,请看下面的答案 here 这增加了 dataType: 'json' 到ajax调用,该调用强制jQuery将响应视为json对象。请注意所提到的注释,您可能还需要在服务器上设置正确的内容类型头,以便服务器将其视为正确的内容类型头。

    Parse JSON from JQuery.ajax success data