将javascript变量的值插入到php变量中

时间:2013-07-31 18:41:34

标签: php javascript html

我已经看到很多关于将php值放入javascript变量的问题但是我没有看到任何将javascript变量放入php变量的问题。所以我的问题是有没有办法做到这一点,如果是这样,你能帮助我,或者至少指出我正确的方向。

到目前为止,我的代码是:

<script>
function CheckForm()
{
var inputElement = document.getElementsByTagName("input");

if((inputElement[0].value !=="first" && inputElement[0].value !=="") && 
    (inputElement[1].value !=="Initial" && inputElement[1].value !=="") && 
    (inputElement[2].value !=="last" && inputElement[2].value !=="") && 
    (inputElement[3].value !=="someone@example.com" && inputElement[3].value !=="") && 
    (inputElement[4].value !=="") && 
    (inputElement[5].value !=="#" && inputElement[5].value !=="") && 
    (inputElement[6].value !=="Lot" && inputElement[6].value !=="") && 
    (inputElement[7].value !=="Evt. Name" && inputElement[7].value !=="") && 
    (inputElement[8].value !=="xx/xx/xxxx" && inputElement[8].value !=="") && 
    (inputElement[9].value !=="xx/xx/xxxx" && inputElement[9].value !=="") && 
    (inputElement[10].value !=="xx:xx" && inputElement[10].value !=="") &&
    (inputElement[11].value !=="") &&
    (inputElement[12].value !=="xx:xx" && inputElement[12].value !=="") &&
    (inputElement[13].value !=="") &&
    (inputElement[14].value !=="") &&
    (inputElement[15].value !=="") &&
    (inputElement[16].value !=="x.xHours/Time Range" && inputElement[16].value !==""))
{
    SendMail();
}
else
{
    alert("One or more fields were not filled in correctly. Please try again.");
}
}

function GetBody()
{
var inputElement = document.getElementsByTagName("input");
var addInfo = document.getElementsByTagName("textarea");
var msg = "";

var line1= ("First Name: " + inputElement[0].value);
var line2= ("Middle Initial: " + inputElement[1].value);
var line3= ("Last Name: " + inputElement[2].value);
var line4= ("Email: " + inputElement[3].value);
//OTHER LINES OF MESSAGE HERE

msg = (line1 + "\n" + line2 + "\n" + line3 + "\n" + line4 + "\n" + line5 + "\n" + line6 + "\n" + line7 + "\n" + line8 + "\n" + 

line9 + "\n" + line10 + "\n" + line11 + "\n" + line12 + "\n" + line13 + "\n" + line14 + "\n" + line15 + "\n" + line16 + "\n" + 

line17);
return msg;
}

function SendMail()
{
    var to = "someone@something.com"
    var from = document.getElementsByTagName("input")[3].value;
    var subject = "Parking Lot Request";
    var msg = GetBody();

<?php 
$to = "GET to";
$subject =  "GET subject";
$message =  "GET msg";
$from =  "GET from";
$headers = "From: " . $from;
mail($to, $subject, $message, $headers);
mail($from, $subject, $message, $headers);
echo "Request has been sent. Also a copy has been sent to you.";

?>    
}
</script>

1 个答案:

答案 0 :(得分:2)

如果您尝试在同一页面上完成所有操作,则无法完成。 php会在页面到达浏览器之前运行并呈现为HTML和Javascript,因此您的浏览器不可能在同一页面上更改PHP变量。

现在,您绝对可以将AJAX请求发送到服务器上的另一个甚至相同的PHP页面,但PHP也会在您在浏览器中看到结果之前运行并完成。你想让PHP做的任何事情都涉及从Javascript获取变量,你必须使用AJAX。