将值从JS传递给PHP时出错

时间:2012-09-03 22:40:20

标签: php javascript html

我正在尝试使用POST方法将值从javascript传递给php,但它无法正常工作。这是代码:

<head>
<script type="text/javascript">
function Email()
{

    var e=prompt("Your Email","");
    if(e==null||e=="")
    {
    alert("You need to enter an email..Try again");
    Email();
    }

    return e;
}
function Code()
{

    var f=prompt("Activation code","");
    if(f==null||f=="")
    {
    alert("You need to enter the code..Try again");
    Code();
    }

    return f;
}
</script>
</head>
<body>
<form method="post">
<input type="hidden" id="Email" name="Email" />
<input type="hidden" id="Code" name="Code" />
</form> 
<script>
var email=Email();
var code=Code();
document.getElementByID("Email").value=email;
document.getElementByID("Code").value=code;
</script>

<?php
$email=$_POST["Email"];
$code=$_POST["Code"];

echo $email.$code;
?>
</body>

我收到这些错误:

  • 注意:未定义的索引:电子邮件
  • 注意:未定义的索引:代码

任何人请帮帮我......

1 个答案:

答案 0 :(得分:1)

如果你想打印那些你需要创建表单的值,那就是一个正确的表格。如果你只想提交表单,那里不需要JS,因为如果你只想提交一些值而不需要表单,那么你想使用jQuery Post

<form method="post" action="">
    <label for="email">Email</label>
    <input type="text" name="email" />

    <label for="code">Code</label>
    <input type="text" name="code" />

    <input type="submit" value="Submit" />
</form>​

小提琴:here

修改

然后this就是你想要的。 (请注意,此代码使用jQuery库)

$(function(){
    // Create both variables
    var code, email;

    // Ask for code and check if it's not null or empty
    do{
        code = prompt('Activation code', null);
    }
    while(code == null || code == '');


    // Ask for email and check if it's not null or empty
    do{
        email = prompt('Your email', null);
    }
    while(email == null || email == '');

    // Make POST request via AJAX to your script
    $.post('yourscript.php', { code: code, email: email }, function(data) {
        // If success alert response (in your case should be "email.data" values)
        alert(data);
    });   
});