gpt4 book ai didi

javascript - PHP 函数末尾的 0

转载 作者:行者123 更新时间:2023-11-28 18:01:09 24 4
gpt4 key购买 nike

这直接取自W3Schools教程,但我修改了php文件以使用wordpress钩子(Hook)和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 文件本身有关。有什么想法吗?

最佳答案

看起来这是一个 WordPress 问题。他们用 die(0) 响应。

https://wordpress.stackexchange.com/questions/116759/why-does-wordpress-add-0-zero-to-an-ajax-response

关于javascript - PHP 函数末尾的 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43530608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com