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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵