3

一旦选择字段发生更改,我将尝试返回一些元数据。但是,我已经对下面的代码进行了多次迭代,如果我只是从 php 脚本中回显它,它就可以正常工作,但是当我尝试将它作为响应返回时,它会失败。我知道它肯定在运行该功能,因为如果我简单地告诉它'echo'xxxx',它就可以工作。下面是我试图实现的代码。我完全被难住了,希望我只是忽略了一些东西......

add_action('admin_footer', 'get_criteria_javascript');

function get_criteria_javascript() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
    if(jQuery('select#pages').length > 0) {
        jQuery('select#pages').live('change', function() {
            var selected = jQuery(this).val();
            var data = { action: 'get_criteria', post_id: selected };

            jQuery.ajax({
                type: 'post',
                dataType: 'html',
                url: 'admin-ajax.php',
                data: {action: 'get_criteria', post_id : selected },
                success: function(response) {
                    alert(response);
                }
            });
        });
    }
});
</script>
<?php
}

add_action('wp_ajax_get_criteria', 'get_criteria_callback');

// if I use echo get_criteria_callback(627); here, it returns the expected results... 

function get_criteria_callback($post_id) {
    $meta = get_post_meta($post_id, 'criteria');
    $content = implode(', ', $meta[0]); 
/* This is one version. Although I can echo it fine, if I return this as a response, it tells me my implode is using invalid arguments */

    echo $content;
    die();
 }
4

1 回答 1

0

在您的 ajax 调用中,不应硬编码 url 参数,ajaxurl而是使用。ajax 调用是一个新的 http 请求。所以你发送的数据是通过 POST 方法传递的。

function get_get_criteria_callback(){
  $post_id = isset( $_POST['post_id'] ) ? $_POST['post_id'] : false;

  if( $post_id ){
    $meta = get_post_meta($post_id, 'criteria');
    $content = implode( ', ', $meta[0] );
  }

  echo $content;

  die();

}

希望能帮助到你!

于 2013-09-08T10:07:19.353 回答