duanjianshen4871 2017-07-05 14:19 采纳率: 100%
浏览 640
已采纳

http.responseText为空

I have a problem with my http.responseText (is always empty). I post my code:

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;}

If I replace "xhttp.send( datastring_escaped );" with "xhttp.send( datastring );", everything will work as expected. How can I fix the problem. I post also the php code:

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

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

        }

How can I solve the problem? Thanks in advance!!!

Francesco

  • 写回答

1条回答 默认 最新

  • dongwu3596 2017-07-05 14:26
    关注

    encodeURIComponent is only used for a part (component) of the URI.

    encodeURIComponent("firstName=foobar")
    

    will give you "firstName%3Dfoobar". There will be no firstName request parameter and you can't read it from $_POST['firstName'].

    If you really need to encode it, then only encode the firstName variable:

    var datastring_escaped = "firstName=" + encodeURIComponent(firstName);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?