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

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 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景