我想在表单提交事件中从 php 调用一个 javascript 函数。并且该 javascript 函数将访问 php 变量,使用 ajax 将它们发送到另一个网站上的 php 脚本。以下代码只是一个表示。
<?php
....
.....
......
if($_POST["action"]=="xyz"){
$myname = "asim";
echo "<script type='text/javascript'>submitform();</script>";
}
.....
....
...
gotoanotherpagefinally();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function submitform(){
alert("<?php echo $myname; ?>");
$.ajax({
type: 'POST',
data: {
action: 'whatever',
fileID: "<?php echo $myname; ?>",
},
url: 'http://xyz.com/API/query.php'
});
}
</script>
</head>
<body>
<form id="myform">
------
------
<input type="submit" name="submit_details">
</form>
</body>
</html>
我需要从 php 调用 javascript 函数,因为 js 函数采用的 php 变量仅由 php 本身设置,而不是表单值或其他东西。
最佳答案
您可以使用 jQuery 捕获 submit
事件:
$("#myform").submit(function(e) {
// needed so the default action isn't called
//(in this case, regulary submit the form)
e.preventDefault();
$.ajax(...);
});
关于php - 如何在表单提交事件中从 PHP 调用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18289935/