【问题标题】:Running PHP from JavaScript asynchronously从 JavaScript 异步运行 PHP
【发布时间】:2016-02-01 01:42:52
【问题描述】:

当我以 HTML 形式编写内容时,我试图获得一些建议。

因此,当在该表单上触发 onkeypressonkeyup 事件时,我会调用 JS 函数。在 JS 函数中,我使用 HTTP 请求对象并从 PHP 文件中获取数据。

这是一个小sn-p,可以说明我在做什么。

HTML 代码:

<form class="login" onsubmit="return isvalidated()" action="asd.php" method="post">
			<input id="userID" type="text" onkeypress="checkusername()" onkeyup="checkusername()" onblur="usercheckLv()" placeholder="username" name="user"><br><span class="errors" id="usererror"></span><br>
			<input id="passwordID" type="password" onblur="passwordcheckLv()" placeholder="password" name="password"><br><span class="errors" id="passworderror"></span><br>
			<input type="submit" value="Login">
</form>
<script src="js/index.js"></script>

JavaScipt 代码:

function checkusername(){
	var xmlhttp = new XMLHttpRequest();
       	xmlhttp.onreadystatechange = function() {
           	if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
           	   	document.getElementById("usererror").innerHTML = xmlhttp.responseText;
            	}
       	xmlhttp.open("GET", "xx.php", true);
       	xmlhttp.send();
	}
}

PHP 文件 xx.php:

<?php
    echo "fgfwegfdg";
?>

我的 HTML 文件位于名为 taxi 的文件夹中,index.jsxx.php 位于 taxi/js 文件夹中。

所有其他功能usercheckLv() passwordcheckLv() isvalidated() 都在index.js 文件中,并且所有这些功能都正常工作。正在调用checkusername()(我已经调试过了)。

但是checkusername() 中的内部函数不起作用。

请帮忙。提前致谢。

注意:我在 Ubuntu 中通过 localhost 运行文件

【问题讨论】:

  • 浏览器控制台有错误吗?
  • 浏览器控制台没有错误。一旦我在用户名中按下一个键,我就希望将“fgfwegfdg”写入用户错误。但这并没有发生
  • html & xx.php 文件的位置在哪里?两个文件在同一个文件夹还是不同文件夹?
  • 如果你去localhost/xx.php你会看到你的结果吗?
  • 我的 HTML 文件位于名为出租车的文件夹中。 index.js 和 xx.php 在taxi/js 文件夹中。

标签: javascript php html ajax


【解决方案1】:

如果 checkusername 函数被调用但没有响应,那么问题一定出在您的 Ajax 调用上。

我建议你仔细阅读你的每一行函数代码,因为它们是区分大小写的,尤其是其中的 xhttp 部分。检查 w3school 的语法是否正确。

或者;使用 if(xhttp.statusText === 'OK') 假设 if (xmlhttp.readyState == 4 && xmlhttp.status == 200)。您还可以在您的代码中添加 console.log() 消息以了解代码中断的位置。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 2011-08-19
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多