PHP脚本是表单填写后执行的php脚本:
<?php
$connect = mysql_connect($h, $u, $p) or die ("Connect Submit at this time.");
mysql_select_db($db);
## Escape bad input including '/', '"', etc
////////////////////////////////////////////////////////////////
if(!empty($_POST['InterestedEmail']))
$subscriberEmail=mysql_real_escape_string($_POST['InterestedEmail']);
////////////////////////////////////////////////////////////////
if(!empty($_POST['InterestedBrowser']))
$subscriberBrowser=mysql_real_escape_string($_POST['InterestedBrowser']);
////////////////////////////////////////////////////////////////
## check for nmll values, if all are set, INSERT
if (isset($_POST['submit'])) {
$query="INSERT INTO launching(lauEmail, lauBrowser)
values('$subscriberEmail', '$subscriberBrowser')";
mysql_query($query) or die(mysql_error());
#HERE
}
?>如何让PHP在脚本到达#HERE后运行以下JS代码:#HERE
发布于 2011-11-16 21:42:42
您可以结束PHP并重新启动它,只需将JS放在其中,或者如果您想将它嵌入到PHP中,这里有#,那么回显/打印它怎么样:
echo "<script type=\"text/javascript\">";
echo "window.alert('Submitted. Thank you.')";
echo "</script>"; 发布于 2011-11-16 21:54:46
您混淆了服务器端和客户端脚本。PHP运行在服务器上,JS运行在客户机上。没有办法让PHP显示警报或运行任何JS代码,客户机/浏览器必须这样做。虽然您可以输出一个简单的JS片段来实现这一点,但是您强迫用户重新加载页面(这很可能包含他们刚刚填写的表单,这让人困惑,或者是一个带有单个警报的空白页面)。
一种更加直观和用户友好的方法是使用AJAX来防止重新加载表单提交的页面。下面是一个使用jQuery的简单示例
<script type="text/javascript">
// Send an AJAX request to the server
$.ajax({
type: 'POST',
url: 'http://www.example', // Change this to your URL
data: { submit: 'true', InterestedEmail: 'something', InterestedBrowser: 'something' }, // Fetch the data from the <input> elements here
success:function(data){
if( data.success) {
window.alert('Submitted. Thank you.');
}
},
});
</script>然后,修改PHP脚本以发送某种响应(我使用的是JSON):
if( isset($_POST['submit']))
{
...
echo json_encode( array( 'success' => true));
exit;
}但是,这个示例是不完整的,因为您需要为通过AJAX返回的任何数据发送一个JSON编码的响应。
https://stackoverflow.com/questions/8159041
复制相似问题