【发布时间】:2017-09-17 17:48:29
【问题描述】:
这是直接取自这个 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 文件本身有关。有什么想法吗?
【问题讨论】:
-
在本地测试了php,没有“0”你确定这是整个php文件吗?
标签: javascript php html ajax wordpress