ajax请求不发布表单数据

时间:2013-09-08 01:13:24

标签: php javascript ajax

我遇到一个问题,即我的登录表单中输入的值(电子邮件和密码)未被解析为我的服务器php脚本。

我的ajax请求:

function signin(){
var loginEmail = gebi("loginEmail").value;
var loginPass = gebi("loginPass").value;

if(loginEmail == "" || loginPass == ""){
    gebi("loginEmail").style.borderColor = "red";
    gebi("loginPass").style.borderColor = "red";
} else {
    gebi("signinBtn").style.display = "none";

            //Declare ajax request variables
    hr = new XMLHttpRequest();
    url = "main.php";
    vars = "email="+loginEmail+"&pass="+loginPass;

    //Open the PHP file that is receiving the request
    hr.open("POST", url, true);

    //Set content type header info for sending url ecncoded variable in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    //Trim string data before sending it
    if (!String.prototype.trim) {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }

    //Access the onreadystatechange event for the XMLHttpRequest
    hr.onreadystatechange = function() {
        if (hr.readyState == 4 && hr.status == 200) {
            var responseText = hr.responseText.trim();
            if (responseText != "signin_failed") { 
                console.log(responseText);
            } else {
                console.log(responseText);
                gebi("signinBtn").style.display = "block";
                gebi("loginEmail").style.borderColor = "red";
                gebi("loginPass").style.borderColor = "red";
            }
        }
    }
    //Send the data to the PHP file for processing and wait for responseText
    hr.send(vars);
}
}

当php脚本使用以下代码返回值时:

if (isset($_POST["email"])) {
    echo 'email = '+$_POST["email"];
}

即使表单字段中存在数据,记录到控制台的返回值也为“0”。

出了什么问题?

1 个答案:

答案 0 :(得分:2)

问题出在您的PHP脚本中。如果您尝试在PHP中连接字符串,请使用点.+用于连接javascript等语言中的字符串。

echo 'email = ' . $_POST["email"];