javascript - WordPress 使用 json_encode 将帖子从 php 手动发送到 js,并将帖子 ID 发送到 div

标签 javascript php json wordpress

我习惯于按照以下代码行将帖子作为数组获取,然后将其发送回请求它的 js,方法是使用 json_encode 将帖子传输到 JSON

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"}]

所以它基本上是一个包含 2 个帖子对象的对象。我如何处理此处帖子的属性?

最佳答案

看起来您想将响应解析为 JSON,请查看这个答案 heredataType: 'json' 添加到 ajax 调用中,强制 jQuery 将响应视为 json 对象。请注意提到的注释,您可能还需要在服务器上设置正确的 Content-Type header ,以便服务器如此对待它。

Parse JSON from JQuery.ajax success data

关于javascript - WordPress 使用 json_encode 将帖子从 php 手动发送到 js,并将帖子 ID 发送到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50401874/

相关文章:

javascript - 将参数作为字符串传递包含javascript onclick函数中的空格

json - 如何定义至少需要许多属性之一的 JSON 模式

jquery - 解析嵌套的 json 对象

json - 在配置单元数据类型中, map 比 JSON 字符串快多少?

php - 使用 mysqli 检索数组

javascript - AngularJS 更新范围 $q

javascript - AddThis 工具箱和 IE7

javascript - 更新嵌套 Redux reducer 对象的值

PHP OOP - 类内的 MySQL 连接

php - Hooks around 添​​加到 Woocommerce 的购物车