2

好的,所以我的想法是,一旦满足 php 中的 if 语句,我需要一段 javascript 来运行,但这需要与 dom 交互,因此假设按下按钮并且在按下按钮时将变量传递给 php . (这不是那个 senario 但相当相似):

if ($button == 1){
    echo '<script type="text/javascript"> document.getElementById("myForm").submit(); </script>';
}

我希望一旦满足此条件,此代码就可以运行。它需要在 php if 语句中,我无法将其移至 js。但是我确实考虑过尝试将代码添加到变量中并通过 ajax 将该变量传递给 js,但没有奏效。

任何帮助将非常感激。

4

1 回答 1

1

do you mean just wanting to run a piece of javascript, after a php condition is met? If so:

myScript.php

<?php
    $button = 1;
    if ($button == 1){
      echo "submit form";
    }
?>

myScript.js

$.ajax({
  type:"POST"
  url:"myScript.php"
  success: function(data){
    if(data == "submit form"){
      //submits "myForm"
      $("#myForm").submit();
    }
  }
});

as said by SLaks, its not possible to execute javascript in php, because php runs on the server, and javascript runs on the client. to make it easier to understand: they are basically 2 seperate "worlds" which can only run certain code.

于 2013-04-07T16:00:30.973 回答