猿问

使用 ajax 重新加载特定元素

我在一个 wordpress 网站工作。我使用名为 my cred 的插件,因此任何用户都有积分余额。它显示在每一页上。问题是当用户花费积分时,余额不会改变,除非用户重新加载页面并且很烦人。我决定使用 AJAX 每 2 秒重新加载一次元素(这是最好的主意吗?)


我浏览了 stackoverflow 并找到了有关如何使用 AJAX 重新加载 div 元素的答案,但我根本不明白。


<div id="balance" align="right"

     <strong><strong></strong>


        <?php if (  is_user_logged_in() ) {


        echo '<strong>Balance: </strong>'.do_shortcode( '[mycred_my_balance wrapper=0 title_el="" balance_el=""]', $ignore_html = false ).'♥'.'';


        echo '<a href="cumpara-sau-castiga"

>

</a>';}





?>

我想要的只是在用户花费点数而不对服务器施加压力时重新加载它的最佳方式。提前致谢。


POPMUISE
浏览 182回答 1
1回答

慕码人2483693

//将此代码添加到您的functions.phpadd_action( 'init', 'my_script_enqueuer' );function my_script_enqueuer() {&nbsp; &nbsp;wp_localize_script( 'reloadVars', 'custom_vars', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));}add_action("wp_ajax_reload_balance", "reload_balance");add_action("wp_ajax_nopriv_reload_balance", "reload_balance");function reload_balance() {&nbsp; &nbsp; $balance = "";&nbsp; &nbsp; if (&nbsp; is_user_logged_in() ) {&nbsp; &nbsp; &nbsp; &nbsp; $balance .= '<strong>Balance: </strong>'.do_shortcode( '[mycred_my_balance wrapper=0 title_el="" balance_el=""]', $ignore_html = false ).'♥'.'';&nbsp; &nbsp; &nbsp; &nbsp; $balance .= '<a href="cumpara-sau-castiga"></a>';&nbsp; &nbsp; }&nbsp; &nbsp; echo $balance;&nbsp; &nbsp; wp_die();}//Add this code either on your js file or in footer.php<script>setInterval(function(){&nbsp;jQuery.ajax({&nbsp; &nbsp;type : "post",&nbsp; &nbsp;url : ajaxurl,&nbsp; &nbsp;data : {action: "reload_balance"},&nbsp; &nbsp;success: function(response) {&nbsp; &nbsp; &nbsp; jQuery("#balance").html(response);&nbsp; &nbsp;}&nbsp;});}, 3000);
随时随地看视频慕课网APP
我要回答