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

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装