为什么XMLHttpRequest没有响应?

3
我正在尝试从连接到数据库的PHP文件中获取一些结果,但是发送到数据库的变量并未来自XMLHttpRequest。
HTML代码如下:

The 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 索引未定义。

尝试将 var userName = uname.value; 更改为 var userName = 'userName=' + uname.value;。在向 Ajax 传递数据时,您需要使用查询格式:fieldname=value&anotherfield=somevalue。_注意:_向函数传递变量时,变量名称不会被传递,因此您的变量称为userName是无关紧要的。 - M. Eriksson
3个回答

0

试试这个。应该可以解决问题。

var userName = uname.value;
xhr.send("data" + userName); 

而你的 PHP 应该像这样处理。在这种情况下,将其放入变量 ($response) 中,并在代码末尾回显该变量。

$data = $_POST['data'];
if(isset($_POST['data'])){
$username = $_POST['data'];
} else {
$username = "Data Not Set"}
echo $username;

0
如上面的评论所指出的,您没有正确地分配POST变量 - 每个都应该是一个“名称/值”对,因此在这种情况下,您将设置名称为“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 );

0

你需要在你的 PHP 代码中添加 file_get_contents 函数。

    $uname = file_get_contents("php://input");
if(isset($uname)){
   echo $uname;
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接