jQuery Ajax passing value on php same page

前端 未结 2 1494
别跟我提以往
别跟我提以往 2020-11-28 13:51

I am kinda confused on it, when trying to send value on the same page.

 

        
相关标签:
2条回答
  • 2020-11-28 14:32

    You should wrap your code with

    $(document).ready(function(){
       // your code here
    });
    

    This way, it will only run when the browser finishes processing the structure of your HTML.

    UPDATE

    There was a lot of debug stuff on your code, try this (requires Firebug to see the output of the ajax request):

    <script>
    $(document).ready(function(){
        $("select[name='sweets']").change(function () {
            jQuery.ajax({
                type: "POST",
                data:  $("form#a").serialize(),
                success: function(data) {
                    // Check the output of ajax call on firebug console
                    console.log(data);
                }
            });
        });
    });
    </script>
    
    0 讨论(0)
  • 2020-11-28 14:34

    Here is the working code for you. To send ajax request to the same page you can keep url parameter empty, which you are already doing. If you are trying to make the script behave differently when $_POST has value then use isset as I have used below.

     <?php
      if(isset($_POST['sweets'])) 
      {
        echo $_POST['sweets'];
        exit;
      }
      ?>
    
        <script>
            $(function(){
              $("select[name='sweets']").change(function () {
              var str = "";
              $("select[name='sweets'] option:selected").each(function () {
                    str += $(this).text() + " ";
    
                  });
    
                    jQuery.ajax({
                    type: "POST",
                    data:  $("form#a").serialize(),
    
                    success: function(data){
                        jQuery(".res").html(data);
    
                        $('#test').html(data);
    
    
                    }
                    });  
                    var str = $("form").serialize();
                    $(".res").text(str);
            });
            });
            </script>
    
    
     <div id="test">
    
      </div>
    
    <form id="a" action="" method="post">
      <select name="sweets" >
       <option>Chocolate</option>
       <option selected="selected">Candy</option>
       <option>Taffy</option>
       <option>Caramel</option>
       <option>Fudge</option>
      <option>Cookie</option>
    </select>
    </form>
    
    0 讨论(0)
提交回复
热议问题