使用jQuery从PHP获取变量值 [英] Getting variable value from PHP with jQuery
问题描述
那我怎么用jquery从php文件中获取变量值呢? jQuery代码在其他文件(tpl)中
So how do i get variable value from php file with jquery...? the jquery code is in other file (tpl)
例如,我有register.php和register.tpl(register.php的模板文件)
for example i have register.php and register.tpl (template file for register.php)
register.php
...some includes here...
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string(trim($_POST['username']));
$email = mysql_real_escape_string(trim($_POST['email']));
$check = $mysql->query("SELECT username FROM ".TBL_USERS." WHERE username = '".$username."' OR email = '".$email."'");
$rows_check = mysql_num_rows($check);
if($rows_check > 0) {
echo 1;
} else {
$password = mysql_real_escape_string($_POST['password']);
$salt = generate_salt($email);
$hash = hash_password($password, $salt);
$q = $mysql->query("INSERT INTO ".TBL_USERS." (username, password, email, salt) VALUES ('".$username."', '".$hash."', '".$email."', '".$salt."')");
if($q) {
header("Location: index.php");
} else {
die(mysql_error());
}
}
} else {
.. calling parse template function ...
}
register.tpl
..jquery library included..
<form id="register" action="register.php" method="post">
<tr>
<td>Username</td>
<td><input type="text" id="username" name="username" class="register" style="width: 200px;" />
</td>
电子邮件 ...其他输入... $(#username").blur(function() {
email ...other inputs... $("#username").blur(function() {
var email_v = $("#email").val();
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
$.post("register.php",{ username:$(this).val(), email: email_v, submit: true } ,function(data)
{
if(data=="1")
{
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
</script>
当我出于测试目的将整个register.php更改为 或者 该脚本有效...但是在原始版本中,该脚本始终显示用户名可用...
when i changed the whole register.php for testing purposes to or the script worked...however with the original version it shows always that username is available...
推荐答案
最好的选择是将PHP变量输出为隐藏字段或JavaScript变量:
Best bet is to output the PHP variable as a hidden field or a JavaScript variable:
<input type="hidden" id="my_var" name="my_var" value="<?php echo($my_var); ?>" />
// access it like this:
alert($('#my_var').val());
或
<script type="text/javascript">
var my_var = <?php echo($my_var); ?>;
</script>
// access it like this
alert(my_var);
应该这样做:-)
这篇关于使用jQuery从PHP获取变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!