Ajax函数最后返回1上的数据

我正在使用 Ajax 获取一些 html 代码。我找回了代码。但最后我得到 1(或 11)。


add_action( 'wp_ajax_nopriv_getCart', 'getCart' );

add_action( 'wp_ajax_getCart', 'getCart' );

function getCart(){

    echo get_cart_content();

    die();

    return;

}

function get_cart_content() {

    $cartContent = '';

    $cartContent = require_once('wps-cart-content.php');

    $cartContent .= require_once('wps-cart-footer.php');

    return $cartContent;

}

$.ajax({

    type: "GET",

    url: '/wp-admin/admin-ajax.php',

    data: {

       action: 'getCart',

    },

    success: function (data) {

        console.log(data);

    },

    error: function (jqXHT, textStatus, errorThrown) 

        {console.log('Fehler');}

});

我注意到,如果我require_once只调用一次,该函数只返回一次 1 。如果我在不调用的情况下返回一个值 get_cart_content(),则代码末尾也没有 1


我尝试了很多……比如 dataType: html 或 json 和 json_decode。我也试过 require, require_once, include_once include 等。代码末尾总是有 11 ......而且如果我记录代码,它会被注释掉,但如果我把它放在我的文档中,它会正常显示。我想这不是问题,但可以提供帮助。


            <!-- <a  href=" " class="button wps-sc-cont btn"></a> -->

    </div>

   </div>   

</div>11


慕侠2389804
浏览 135回答 1
1回答

桃花长相依

我们需要按照下面的方式更改代码。add_action( 'wp_ajax_nopriv_getCart', 'getCart' );add_action( 'wp_ajax_getCart', 'getCart' );function getCart(){&nbsp; &nbsp; $response = array(&nbsp; &nbsp; &nbsp; &nbsp; 'type' => 'success',&nbsp; &nbsp; &nbsp; &nbsp; 'html' => get_cart_content()&nbsp; &nbsp; );&nbsp; &nbsp; wp_send_json_success($response);&nbsp; &nbsp; wp_die();}function get_cart_content() {&nbsp; &nbsp; ob_start();&nbsp; &nbsp; require_once('wps-cart-content.php');&nbsp; &nbsp; require_once('wps-cart-footer.php');&nbsp; &nbsp; return ob_get_clean();}$.ajax({&nbsp; &nbsp; type: "GET",&nbsp; &nbsp; url: '/wp-admin/admin-ajax.php',&nbsp; &nbsp; dataType: 'json',&nbsp; &nbsp; data: {&nbsp; &nbsp; &nbsp; &nbsp;action: 'getCart',&nbsp; &nbsp; },&nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; switch(res.data.type) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case 'success' :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(res.data.html)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case 'failure' :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; error: function (jqXHT, textStatus, errorThrown)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {console.log('Fehler');}});
打开App,查看更多内容
随时随地看视频慕课网APP