Unable to use $.get within WordPress page

2019-08-04 09:48发布

问题:

I'm trying to use an ajax $.get() request to display calculated data within one of my WordPress pages. I haven't decided if I'm going to host the php calculation file on a different server of mine, or the one that WordPress is hosted on (don't think this would make a difference anyway since its a data request). I'm looking to add the following code to either the header.php file, or even better, within the page created in wp-admin:

<script>
  $(document).ready(function(){
      $.get("http://my-other-website.com/parse-list.php",function(data){
          alert(data);
      });
  });
</script>

I know this is a basic function, but I'm just really stumped on how it doesn't work within WordPress, but works when on my other server that doesn't host WordPress. I tested jQuery to make sure it was being loaded properly, with a simple alert("hey");, and the alert works just fine. Has anyone else had this problem? Any help would be greatly appreciated!

回答1:

jQuery in WordPress runs in noConflict mode which means the global $ shortcut for jQuery isn't available. Replace your code with the following:

<script>
  jQuery(document).ready(function($){
      $.get("http://my-other-website.com/parse-list.php",function(data){
          alert(data);
      });
  });
</script>