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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有没有人会打学生成绩管理系统呀
  • ¥15 在使用Fiddler和夜神模拟器抓包的时候一直出现443该怎么办啊QAQ搜了好几个笔记都没有解决
  • ¥15 3x7的二维数组A、B、C,A中的任意1个数组元素与B的任意1个数组元素、同时又与C的任意1个数组元素比较,把不同位置出现相同数的比较称为无意义,反之称为有意义,把有意义的比较打印输出。
  • ¥20 预测模型怎么处理原始数据(随机森林)
  • ¥20 请问discuz3.5如何实现插入ckplayer全能播放器功能呢?
  • ¥15 thingsboard代码编译出错误
  • ¥15 博途v18仿真报错怎么解决
  • ¥15 欧姆龙plc枕式包装机 ST编程
  • ¥15 为啥快手广告联盟的广告这么难出来
  • ¥15 k8s集群重启后,kubelet一直报systemctl restart kubelet.service "Failed to delete cgroup paths"