dongwai4434
2017-05-22 14:55
采纳率: 0%
浏览 98
已采纳

在Javascript上调用PHP函数Onchange

I want to call a function in php onchange in select of html,how can this be done?

html code

<div class="col-sm-4 form-group">
   <label for="c_city">City</label>
   <select class="form-control" id="c_city" onchange="<?php getArea(); ?>">
        <option value="">Select City Name</option>
        <!--populate value using php-->
        <?php
            $stmt ="SELECT * FROM Cities";
            foreach ($con->query($stmt) as $row) {
         ?>
         <option value="<?php echo $row['City_ID'];?>"><?php echo $row['City_Name'];?></option>
         <?php
          }
         ?>
   </select>
</div>

PHP Functions Page

function getArea() 
{
    if(isset($_GET['c_city'])) 
    {
        $c_city = $_GET['c_city'];
        echo $c_city;
    }
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dousi8559 2017-05-22 15:06
    最佳回答

    You can try to use ajax to call the php script and receive results back to javascript.

    For example in your html page:

    <div class="col-sm-4 form-group">
       <label for="c_city">City</label>
       <select class="form-control" id="c_city" onchange="getArea()">
            <option value="">Select City Name</option>
            <!--populate value using php-->
            <?php
                $stmt ="SELECT * FROM Cities";
                foreach ($con->query($stmt) as $row) {
             ?>
             <option value="<?php echo $row['City_ID'];?>"><?php echo $row['City_Name'];?></option>
             <?php
              }
             ?>
       </select>
    </div>
    
    <script>
     function getArea(){
      var c_city = $('#c_city').val();
       $.ajax({
               type: 'POST',
               url: "get_area.php",
               data: {c_city:c_city},
               success: function(result){
                   //do something here with return value like alert
                   alert(result)
               }
         })
    }
    </script>
    

    Then in your php script you can manipulate the value you receive from javascript

    if(isset($_POST['c_city'])) 
        {
            $c_city = $_POST['c_city'];
            echo $c_city;
        }
    

    Let me know if it helps or if you find a problem

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题