PHP函数结束时为0

时间:2017-04-20 21:57:16

标签: javascript php html ajax wordpress

这是直接从这个W3Schools教程中获取的,但是我修改了php文件以使用wordpress钩子和js文件来接收两个变量,这样它就可以在一个页面中多次使用:https://www.w3schools.com/php/php_ajax_php.asp

我有以下gethint.php文件:

<?php
add_action("wp_ajax_GetHint", "GetHintFunction");
add_action("wp_ajax_nopriv_GetHint", "GetHintFunction");

// embed the javascript file that makes the AJAX request
//wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'ajaxtest.js', array( 'jquery' ) );
wp_enqueue_script( 'my-ajax-request', plugins_url( '/js/showHint.js', __FILE__ ), array( 'jquery' ) );

// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

function GetHintFunction(){
    // Array with names
    $a[] = "Anna";
    $a[] = "Brittany";
    $a[] = "Cinderella";
    ...
    $a[] = "Wenche";
    $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;
}

以下showHint.js文件:

function showHint(str, str2) {
    if (str.length == 0) { 
        document.getElementById(str2).innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById(str2).innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", MyAjax.ajaxurl + "?action=GetHint&q=" + str, true);
        xmlhttp.send();
    }
}

这是html页面本身:

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

<p><b>Type another name in the input field below:</b></p>
<form> 
Last name: <input type="text" onkeyup="showHint(this.value, 'txtHint2')">
</form>
<p>Suggestions: <span id="txtHint2"></span></p>

问题是我的输出在响应结束时为零。以下是它的外观: browser screenshot

我使用了chrome的开发人员工具,在XHR下,我可以看到PHP响应本身在响应结束时包含零。即使我从js函数中删除第二个文本框和第二个变量,问题仍然存在,因此问题似乎与php文件本身有关。有什么想法吗?

1 个答案:

答案 0 :(得分:3)