如何从我的php文件中调用位于我的html文件中的javascript函数?

时间:2014-05-28 04:48:04

标签: javascript php html

index.html我有:

<head>
  <link rel="stylesheet" href="css/messi.min.css" />
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script src="js/messi.min.js"></script>
  <script type="text/javascript">
    function failureFunction(){
      new Messi('There was an error sending your message.', {title: 'Failure'});
    };      
    function successFunction(){
      new Messi('Success sending email', {title: 'Success'});
    };
  </script>
</head>
<body>
  <form class="form" id="form1" method="post" action="contactengine.php">
  ...
  </form>
</body>

然后在我的contactengine.php我有:

$success = mail($EmailTo, $Subject, $Body, $Headers);

// redirect to success page 
if ($success){
  echo "<script type='text/javascript'>successFunction();</script>"; 
  print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">";
}
else{
 echo "<script type='text/javascript'>failureFunction();</script>";
 print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">";
}

我的回声......虽然没有打电话给successFunction()。我知道$success var是真的,因为如果我在那里发出警报,它会调用警报,我知道我的successFunction()有效,因为我可以从我的index.html文件中调用它而没有任何问题。梅西图书馆位于here以供参考。

如何从我的php文件中正确调用successFuntion()

1 个答案:

答案 0 :(得分:3)

可能您可以在javascript文件中移动JS函数,并将该文件包含在需要调用这些函数的PHP或HTML页面中。

JS / customMessi.js

function failureFunction(){
  new Messi('There was an error sending your message.', {title: 'Failure'});
};      
function successFunction(){
  new Messi('Success sending email', {title: 'Success'});
};

并在您的HTML文件中:

<head>
 <link rel="stylesheet" href="css/messi.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">   </script>
 <script src="js/messi.min.js"></script>
 <script src="js/customMessi.js"></script>
 </head>
<body>
 <form class="form" id="form1" method="post" action="contactengine.php">
   ...
  </form>
</body>

以及contactengine.php文件中:

echo "<script type='text/javascript' src='js/customMessi.js'></script>";
...
$success = mail($EmailTo, $Subject, $Body, $Headers);

// redirect to success page 
if ($success){
  echo "<script type='text/javascript'>successFunction();</script>"; 
  print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">";
}
else{
 echo "<script type='text/javascript'>failureFunction();</script>";
 print "<meta http-equiv=\"refresh\" content=\"0;URL=index.html\">";
}