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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器