简体   繁体   中英

$.get within a .click function

Not really sure where I'm going wrong with this one. I have a button element that when clicked, I want the following script below to be triggered. No issues seemingly in Chrome when I click the button but the file isn't fetched.

Am I missing something silly in my .click?

  <script>
        $( "button" ).click(function() {
            $.get("testimg.php", function() {
                alert("Success!");
            });
        });
    </script>

Your code seems right. You need to make sure 2 things:

  1. testimg.php (with m) file exists in the same directory.
  2. The <button> is in the DOM when the script runs. I recommend using $(document).ready() event:

     <script> $(document).ready(function(){ $( "button" ).click(function() { $.get("testimg.php", function() { alert("Success!"); }); }); }); </script> 

Working jsFiddle

Worth making it a jQuery.ajax call so you can trace errors.

$(function () {
  $("button").click(function(e) {
    e.preventDefault();
    $.ajax({
      url: "testimg.php",
      success: function () {
         alert("Success!");
      },
      error: function(x,y,z) {
        alert(z);
      }
    });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM