如何在AJAX调用中声明JS变量

时间:2011-12-10 作者:Mythical Fish

我正在使用:wp_localize_script( $handle, $namespace, $variables ); 在进行最初的AJAX调用之前声明一些变量,但我想我不能在回调函数中再次执行同样的操作?我需要声明一个新创建的ID以便在另一个函数中使用,最好的方法是什么?

2 个回复
最合适的回答,由SO网友:Chris_O 整理而成

正确的方法是将数据发布回WordPress admin ajax url,然后在PHP函数中使用$_POST 变量。

将类别id传递回wordpress的jQuery函数示例:

function cat_edit_get() {
    jQuery( "#loading-animation").show();
    var catID = jQuery("#cat :selected").val();
    var text = jQuery("#cat :selected").text();
    jQuery(\'#replace\').html(text);

    jQuery.ajax({
        type: \'POST\',
        url: ajaxurl,
        data: {"action": "cat-editor-get", cat: catID },
        success: function(response) {
            jQuery("#the-list").html(response);
            jQuery("#loading-animation").hide();
            return false;

        }
    });

}
然后您可以通过挂接到wp_ajax 行动这里我只传递从下拉选择中选择的类别id:

add_action ( \'wp_ajax_cat-editor-get\', \'cat_editor_get\' );
    function cat_editor_get () {
        $cat_id = $_POST[ \'cat\' ];
        $preview_cats = get_post_meta ( 82799, \'_\' . $cat_id . \'saved\', true );
        $item_order = $preview_cats[ \'cat_order\' ];
        $post_ids = explode ( ",", $item_order, 30 );
        global $post;
        if ( count ( $post_ids ) < 5 ) {
            $args = array (
                \'category_id\' => $cat_id,
                \'length\' => 30,

            );

            $post_ids = wndsq_get_post_ids ( $args );
        }

SO网友:Joshua Abenazer

可以做的是分解函数,让第一个函数调用返回新创建的ID作为响应。然后你可以做出回应并使用wp_localize_script() 将ID传递给位于脚本文件的其他函数调用,然后执行函数调用。我还没试过这个,但我觉得这个应该有用。

结束