http.responseText为空

时间:2017-07-05 14:19:26

标签: php ajax

我的http.responseText有问题(总是为空)。我发布了我的代码:

function bCheckName ()
{
// It checks if the browser can allow a http request 
if ( window.XMLHttpRequest ) 
{
    xhttp = new XMLHttpRequest();
} 
else 
{
    // for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

// It takes the name from the form
var firstName = document.getElementById("firstName").value;
var datastring = "firstName=" + firstName;
var datastring_escaped = encodeURIComponent ( datastring );

// It opens the request to thye server
xhttp.open ( "POST", "../form/formValidation.php", true );

// It sets the header
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// It sends the data to the server
xhttp.send( datastring_escaped );

// It takes the responde from the server
xhttp.onreadystatechange = function() 
{
    if ( xhttp.readyState == 4 && xhttp.status == 200 ) 
    {

        var string      = xhttp.responseText.substr ( 0, 2 );
        var response    = xhttp.responseText.substr ( 5 );

        if ( string == "OK")
        {
            document.getElementById("nameResponse").innerHTML           = '<img src = "../img/pages/contact/true.png" alt = "correct answer" >';
            document.getElementById("response").innerHTML               = response;
        }
        else
        {
            document.getElementById("nameResponse").innerHTML           = '<img src = "../img/pages/contact/error.png" alt = "wrong answer">';
            document.getElementById("response").innerHTML               = response; 
        }
    }
}

return false;}

如果我替换“xhttp.send(datastring_escaped);”使用“xhttp.send(datastring);”,一切都将按预期工作。我该如何解决这个问题。我也发布了php代码:

        if ( isset( $_POST['firstName'] ))
        {

        echo( "OK - ".urldecode ( $_POST['firstName']) );

        }

我该如何解决这个问题? 在此先感谢!!!

弗朗西斯

1 个答案:

答案 0 :(得分:1)

encodeURIComponent仅用于URI的一部分(组件)。

encodeURIComponent("firstName=foobar")

会给你"firstName%3Dfoobar"。没有firstName请求参数,您无法从$_POST['firstName']中读取它。

如果您确实需要对其进行编码,则只对firstName变量进行编码:

var datastring_escaped = "firstName=" + encodeURIComponent(firstName);