1

我想在表单提交事件中从 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 本身设置,而不是表单值或其他东西。

4

4 回答 4

1

you can use :

<form id="myform" onsubmit="submitform()">
于 2013-08-17T14:49:22.120 回答
1

submit您可以使用 jQuery捕获事件:

$("#myform").submit(function(e) {
  // needed so the default action isn't called 
  //(in this case, regulary submit the form)
  e.preventDefault(); 

  $.ajax(...);
});
于 2013-08-17T14:40:39.140 回答
0

请更改您的代码 -

<?php
   $myname="asim";
?>
<script type="text/javascript">
    function submitform(myname){
        alert(myname);
        $.ajax({
                type: 'POST',
                data: {
                    action: 'whatever',
                    fileID: myname,
                },
                url: 'http://xyz.com/API/query.php'
            });
    }
</script>

HTML

<form id="myform" onsubmit="submitform('<?php echo $myname;?>')">
  ------
  ------
  <input type="submit" name="submit_details">

</form>
于 2013-08-17T18:42:41.550 回答
0

您可以使用 jQuery 来执行此操作。

$(':input').click(function(){});

然后在此函数中,您可以使用 ajax 请求将变量发送到您拥有的 php 页面。

var variableA, variableB; // variables to be initiated by an ajax request

// ajax request to get variables from php page
$.ajax(
{
  url:'php_page_path/source_page.php',
  data:"message=getVars",
  type: 'post',
  success: function(data){
  // use the data from response
    var obj = JSON.parse(data);
    variableA = obj.varA;
    variableB = obj.varB;
  }
});


// use the variables in this ajax request and do what you want
$.ajax(
{
  url:'php_page_path/page.php',
  data:"var1="+variableA+"&variableB="+vaiableB ,
  type: 'post',
  success: function(j){
    // use the data from response
  }
});
于 2013-08-17T14:46:30.800 回答