gpt4 book ai didi

javascript - 为什么 XMLHttpRequest 没有返回响应?

转载 作者:搜寻专家 更新时间:2023-10-31 21:48:51 25 4
gpt4 key购买 nike

我想从连接到数据库的 PHP 文件中获取一些结果,但是发送到数据库的变量不是从 XMLHttpRequest 发送的。

HTML:

<input type="text" id="name"/>

这是JS:

var uname = document.getElementById('name');
function checkUser(){

var xhr = new XMLHttpRequest();
xhr.open("POST" , 'file.php' , true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200)
{
console.log(xhr.responseText);
}
}
var userName = uname.value;
xhr.send(userName);
}
uname.addEventListener("blur" , checkUser);

PHP:

if(isset($_POST['userName'])){
echo $_POST['userName'];
}

如果我删除条件,我会收到一条消息,指出未定义 userName 索引。

最佳答案

正如上面的评论中所指出的,您没有正确分配 POST 变量 - 每个变量都应该是一个 name/value 对,因此在这种情况下您可以将名称设置为 userName 和来自表单元素的值的值。

function checkUser(){
var xhr = new XMLHttpRequest();
xhr.open( 'POST', 'file.php', true );
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200)
{
console.log(xhr.responseText);
}
}
/* As the function was bound to the input you can use `this` to get the value */
xhr.send( 'userName='+this.value );
}

var uname = document.getElementById('name');
uname.addEventListener('blur' , checkUser.bind( uname ), false );/* bind function to field */

或者,更灵活的方法是使用一个小函数来执行 ajax 请求,该函数可用于多次调用,而无需重复重写相同的代码。

function ajax( url, params, callback ){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if( this.readyState == 4 && this.status == 200 ) callback.call( this, this.response );
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send( params );
}



function checkUser(){
ajax.call( this, 'file.php', 'username='+this.value, function(r){
console.log( r );
});
}

var uname = document.getElementById('name');
uname.addEventListener('blur' , checkUser.bind( uname ), false );

关于javascript - 为什么 XMLHttpRequest 没有返回响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48576918/

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