发送到PHP时收到Javascript变量时遇到问题

时间:2014-12-09 23:00:11

标签: javascript php ajax

问题:无法接收发送到我的PHP文档的内容。

使用Javascript:

$('#form_id').submit(function(event){
    event.preventDefault();
    event.stopPropagation();
    var message;
    var myRegExp = validation stuff
    var urlToValidate = document.getElementById("url").value;
    if (!myRegExp.test(urlToValidate)){
        }else{
    var code = (urlToValidate).slice(-22)
    var request = new XMLHttpRequest();

    request.addEventListener('readystatechange', function(event){
    if (this.readyState == 4){
        if (this.status ==200){
            console.log (this.status);
        }else{
            console.log('Server replied with HTTP status ' + this.status);
        }
    }
});

request.open('POST', 'php/submit.php', true);
request.setRequestHeader('Content-Type', 'text/plain');

request.send("code=" + code);
}   
});

然后我在php / submit.php上使用这段代码:

if (!empty($_POST['code'])) { 
    $code = $_POST['code'];
    echo $code; 
};

我觉得我没有为PHP使用正确的标签名称,因为我是所有这些的新手。我会注意到我正在使用表单ID,但是从输入中获取值。

漫记 我正在尝试将已经过验证和切片的用户输入发送到mySQL数据库。

我用javascript实现了我想要的字符串并将其传递给变量。

我正在尝试使用request.send(the_javaS_variable)将其发送到另一个文件夹中的单独php文件。

现在在控制台中,我可以看到变量保存了正确的文本值,我看到它以状态4和200发送。

但它从未出现在submit.php页面上。

1 个答案:

答案 0 :(得分:1)

尝试此操作并移除console.log()

$('#form_id').submit(function(event){
    var myRegExp = validation stuff
    var urlToValidate = document.getElementById("url").value;
    if (!myRegExp.test(urlToValidate)){
        // failed
    }else{

        var code = 'code='+(urlToValidate).slice(-22);

        $.post('php/submit.php', code, function() {
            //   success stuff
        });

    }
    return false;
});