猿问

如何在WordPress短代码中使用Ajax?

如何在WordPress短代码中使用Ajax?

我有个代码可以显示一个随机引号。一个人编写了一个函数来实现所有这些。但是,由于某种原因,通过Ajax更新数据不起作用。当你按下“新引号”按钮时,什么都不会发生。也许有人知道原因?在下面的代码中需要修正什么,以便当您单击“新引号”时加载一个新的引号?

PHP

/wp-content/themes/%your_theme%/js/ajax-load-quote.php

 <?php /* uncomment the below, if you want to use native WP functions in this file */// require_once('../../../../wp-load.php');

 $array = file( $_POST['file_path'] ); // file path in $_POST, as from the js
 $r = rand( 0, count($array) - 1 );

 return '<p>' . $array[$r] . '</p>';
 ?>

HTML结构

在页面内容、小部件或模板文件中:

<div id="randomquotes">
    <p>I would rather have my ignorance than another man’s knowledge,
       because I have so much more of it.<br />
       -- Mark Twain, American author & Playwright</p></div><a id="newquote" class="button" href="#" title="Gimme a new one!">New Quote</a>

显然你可以根据你的喜好来调整,但是为了这个例子,这就是我们要做的。
稍后我们将通过一个短代码生成上面的内容。

jQuery

/wp-content/themes/%your_theme%/js/ajax-load-quote.js

function ajaxQuote() {
    var theQuote = jQuery.ajax({
        type: 'POST',
        url: ajaxParams.themeURI+'js/ajax-load-quote.php',
        /* supplying the file path to the ajax loaded php as a $_POST variable */
        data: { file_path: ajaxParams.filePath },
        beforeSend: function() {
            ajaxLoadingScreen(true,'#randomquotes');
        },
        success: function(data) {
            jQuery('#randomquotes').find('p').remove();
            jQuery('#randomquotes').prepend(data);
        },
        complete: function() {
            ajaxLoadingScreen(false,'#randomquotes');
        }
    });

如何使用WordPress中的Ajax更新页面上的内容?


HUWWW
浏览 573回答 3
3回答

ABOUTYOU

WordPress的短代码和给出参数的函数一样,为了创建Ajax请求,可以在头文件或函数文件中使用jQuery.ajax或xmlhttpadd_action wp_head钩子。您应该在主题文件夹中创建ajax.php,在文件顶部应该包含wp-load.php。并以适当的方式放置所有Ajax函数。
随时随地看视频慕课网APP
我要回答