douyin9987
2014-05-31 11:06
浏览 34

调用表单php里面的一个函数jquery [复制]

This question already has an answer here:

i'd like to call a jquery function from php. I tried this way, but the jquery functions are not called.

jq.action.js

$(function() {

  $("#reset" ).click(function(e){       
    e.preventDefault();
    reset_fields();
  });

  function reset_fields(){
    $(":input").prop('selectedIndex', 0);
  }

  function error_msg(){
    alert("Error");
  }

});

index.php

<script type='text/javascript' src='jquery-1.11.1.min.js'></script>
<script type='text/javascript' src='jq.action.js'></script> 

<?php
if ($_POST['id'] == '1') {

       echo '<script>reset_fields();</script>';

} else {

       echo '<script>error_msg();</script>';
}
?>

ReferenceError: reset_fields is not defined

how can I call from php the functions inside jquery? thanks!

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douche3791 2014-05-31 11:34
    已采纳

    Your problem is JavaScript scoping: the function you're trying to call is not accessible from everywhere.

    $(function() {
        function reset_fields(){
            // this function is only accessible to things inside $(function(){...
        }
    }
    

    That means that you can't access it directly. However, if you place the function outside, it will work:

    function reset_fields() {
        // now this function is globally accessible from anywhere
    }
    
    $(function() {
        // you can still call reset_fields() from here
    }
    
    点赞 打赏 评论
  • douxiajia6309 2014-05-31 11:13

    Php runs on the server and javascript on the client, so the terminology "call a javascript function" is incorrect.

    You can set a javascript variable with php then test that variable with javascript on the client. This will make your code a bit simpler

     var postId = '<?php echo $_POST["id"] ?>';
    
     if( postId === '1'){
      reset_field();
     }
     else {
      reset_field();
     }
    
    点赞 打赏 评论

相关推荐 更多相似问题