我刚刚开始学习javascript,我想知道如何在完成向数据库提交表单后调用PHP中的javascript函数。我的javascript代码基本上是一个警告框,表示您的帐户已创建。任何回应都会有所帮助。这是我要插入函数的PHP代码部分(其他一切无关紧要)和javascript代码插入,如果您需要其他任何请告诉我。非常感谢!
PHP:
<?php
class Registration
{
**FORM VALIDATION AND SUBMISSION NOT INCLUDED**
if ($query_check_user_name->num_rows == 1)
{
$this->errors[] = "Sorry, that user name is already taken. Please choose another one.";
}
else
{
// write new users data into database
$query_new_user_insert = $this->db_connection->query("INSERT INTO users (user_name, user_password_hash, user_email) VALUES('" . $this->user_name . "', '" . $this->user_password_hash . "', '" . $this->user_email . "');");
if ($query_new_user_insert)
{
$this->registration_successful = true;
$this->messages[] = "Registration successful! Please go back to the login page and login in with your new username and password.";
echo "<script type='text/javascript'>myFunction()</script";
}
else
{
$this->errors[] = "Sorry, your registration failed. Please go back and try again.";
}
}
}
else
{
$this->errors[] = "Sorry, no database connection.";
}
}
}
else
{
$this->errors[] = "An unknown error occurred.";
}
}
}
?>
使用Javascript:
<script>
function myFunction()
{
var r = confirm("Registration Successful!\nYou will now be redirected to the login page");
if(r == true)
{
location.assign("http://yhsaa.org/members/index.php");
}
}
</script>
答案 0 :(得分:1)
试试这个:
echo "<script type='text/javascript'>window.onload = function()
{
myFunction();
}
</script>";
正在发生的事情是,此代码在名为onload
的窗口对象上创建事件。当您的html加载完成后,将触发此事件。然后它将调用您的函数myFunction()
。此行为将确保您的函数在之前被声明为,因此它避免了您的函数未声明的异常。
就像改变这一点:
myFunction(); // At this time JS doesn't know that you have an function called myFunction()
function myFunction() {};
到此:
function myFunction() {};
myFunction(); // At this time JS already know your function myFunction() and it will call it.
答案 1 :(得分:0)
您的脚本包含错误,您没有正确关闭脚本标记!