当其他JS脚本包含在html页面中时,Ajax请求不起作用


Ajax Requests don't work when other JS scripts are included in the html page

我正在使用 AJAX 请求从数据库中获取一些数据。我在 HTML 页面中包含四个.js文件。他们是

<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/jqueryui.js"></script>
<script type="text/javascript" src="scripts/framework.plugins.js"></script>
<script type="text/javascript" src="scripts/custom.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $(".buttonid").click(
    function(){
          $.ajax({    //create an ajax request to load_page.php
            type: "POST",
            url: "php/fetch_candidates.php",
            async: true,             
            dataType: "html",   //expect html to be returned   
            error: function(){
                    return true;
            },                       
            success: function(response){                    
                $("#responsecontainer").html(response); 
                //alert(response);
            }
    });
    });
});
</script>

这行不通。但是如果我删除

<script type="text/javascript" src="scripts/framework.plugins.js"></script>
<script type="text/javascript" src="scripts/custom.js"></script>

然后 AJAX 开始工作。我该如何解决这个问题,因为我需要将所有.js文件保存在 html 页面中。

有一个 responsecontainerdiv 处理 html afte rthe ajax 请求。问题仅在于包含这两个js脚本。蒂亚

当其他框架也使用$函数时,它可能会覆盖jQuery的$函数行为。但这会使jQuery变量保持不变。因此,请尝试使用闭包并在 IIFE 中执行它:

(function ($) {
  $(document).ready(function() {
    $(".buttonid").click(function () {
      $.ajax({    //create an ajax request to load_page.php
        type: "POST",
        url: "php/fetch_candidates.php",
        async: true,             
        dataType: "html",   //expect html to be returned   
        error: function(){
          return true;
        },                       
        success: function(response){                    
          $("#responsecontainer").html(response); 
          //alert(response);
        }
      });
    });
  });
})(jQuery);

这会将所有$转换为jQuery的原始函数,并确保你只在jQuery中使用$,而不是任何其他框架,如PrototypeJS或Scriptaculous。

尝试使用 var jq = $.noConflict(); ,就在$(".buttonid").click(之前

并使用jq而不是$,看起来像是一个冲突问题,您能否分享一下framework.plugins.js内部的内容并custom.js