duano3557 2017-04-14 23:36
浏览 52
已采纳

AJAX在Wordpress插件中使用PHP文件

I am following a tutorial on W3Schools for AJAX PHP. https://www.w3schools.com/php/php_ajax_php.asp

Here is the twist: I am doing this in wordpress. The following is a method that DOES work, but it is less than ideal.

1) Create the following gethint.php in the root directory.

<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
...
$a[] = "Vicky";

// get the q parameter from URL
$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from "" 
if ($q !== "") {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            } else {
                $hint .= ", $name";
            }
        }
    }
}

// Output "no suggestion" if no hint was found or output correct values 
echo $hint === "" ? "no suggestion" : $hint;

2) Using the CSS & Javascript toolbox plugin, add this code to the header:

<script>
function showHint(str) {
    if (str.length == 0) { 
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "/gethint.php?q=" + str, true);
        xmlhttp.send();
    }
}
</script>

3) Create a page with the following code (in plain text):

<p><b>Start typing a name in the input field below:</b></p>
<form> 
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>

While this works, having to create a php file and adding to the root directory seems like bad practice. It would be better to have this php file stored in the plugins directory. However that causes this line of the header script to fail as 404:

xmlhttp.open("GET", "/gethint.php?q=" + str, true);

Simply changing the relative path won't work, because theoretically, different users can have their plugin folder in different locations.

I figure I should be using the wp_ajax_ and wp_ajax_nopriv_ hooks, but my attempts I have failed, so I am probably doing it wrong. Please help.

  • 写回答

1条回答 默认 最新

  • dpuwov1487 2017-04-14 23:55
    关注

    Doing ajax in WordPress should all be sent to /wp-admin/admin-ajax.php, to do that, in your plugin's main file or the index.php file, register your ajax action like this:

    // let's do the ajax thing here
    add_action( 'wp_ajax_theNameOfMyCustomAjax', 'theFunctionThatMyAjaxWillCall' );
    
    function theFunctionThatMyAjaxWillCall() {
      // include your ajax file here, in this case
      // I assumed that we placed the gethint.php in 
      // /wp-content/plugins/yourpluginname/gethint.php
      include( plugin_dir_path( __FILE__ ).'gethint.php' );
    
      // don't forget to add "die;" every time you return a response to your ajax
      //Example: echo $hint === "" ? "no suggestion" : $hint; die;
    
      // or you can add the termination code right here
      die; // this will prevent the ajax response to have 0 in the end.
    
    }
    

    Now, in your javascript, instead of calling the filename of your ajax file, you can now use the global ajaxurl javascript variable like this:

    xmlhttp.open("GET", ajaxurl+"?action=theNameOfMyCustomAjax&q=" + str, true);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 全书网Java爬取数据
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥60 为什么使用python对地震数据进行umap降维后,数据成图会出现不连续的现象
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题
  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 安卓qpython向ksweb服务器post文件失败
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败