Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/403.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ajax找不到脚本函数_Javascript_Jquery_Ajax_Scope - Fatal编程技术网

Javascript ajax找不到脚本函数

Javascript ajax找不到脚本函数,javascript,jquery,ajax,scope,Javascript,Jquery,Ajax,Scope,这就是背景: 我有一个脚本,countrySelect.min.js,它被加载到php页面的标题中的其他位置,它不起作用,所以假设这是正确的 <script src="<?php echo base_url(); ?>assets/owlcarousel/owl.carousel.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?&g

这就是背景:

我有一个脚本,countrySelect.min.js,它被加载到php页面的标题中的其他位置,它不起作用,所以假设这是正确的

    <script src="<?php echo base_url(); ?>assets/owlcarousel/owl.carousel.js"></script>

    <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></script>

    <script type="text/javascript" src="<?php echo base_url('assets/js/commonFunctions.js'); ?>"></script>

    <link rel="stylesheet" href="<?php echo base_url('assets/css/countrySelect.css'); ?>">  

    <script type="text/javascript" src="<?php echo base_url('assets/js/countrySelect.min.js'); ?>"></script>

    <link rel="stylesheet" href="<?php echo base_url('assets/css/countrySelectorStyle.css'); ?>">   
此函数几乎在文档末尾调用,但在$document.readyfunction语句之外。它工作正常,没有任何错误

initializeLeafletItems(<?php echo json_encode($offers); ?>); 
就好像函数不在show_函数或ajax调用的相同范围内一样。我觉得这很奇怪;但是,当浏览器调试器停止时,我试图查看看到的范围,并且脚本及其功能似乎已经存在,请查看以下屏幕截图:

我还没有找到很多类似案例的参考资料,当然也没有明确的参考资料,所以对它有一些想法真的很有帮助。在不太类似的情况下,我到处阅读有人建议在ajax调用中重新加载脚本。即使我不知道它是否有效,因为我还没有尝试过,我认为既然脚本已经加载到文档中,那么应该有一种方法在该函数的两个调用中引用它。这是真的吗

更新12/04/2020

将应用它的对象登录到控制台。countrySelect我可以观察到,在下图中留下的工作案例中,有一个链接的countrySelect插件,在不工作的插件中没有

根据countrySelect作者Mark的建议,我在一个更简单的页面上重复了这个测试,我发现它既可以在单击按钮时在本地添加元素,也可以在ajax调用中运行。下面是控制器和查看器的代码;因此,我还尝试在不工作的页面中添加简单的测试,通过单击按钮添加输入元素,而不使用任何ajax。即使在这种情况下,它也不起作用,但在同一页面的第一次下载中,它仍然对元素起作用。有什么想法吗?这似乎是gest在该页面上丢失或交互不好的内容

下面是一个简单页面上的工作代码

控制器:

观众


问题是,在初始化eleafletItems之后,您正在重新初始化jquery;最后打电话。这将重置jquery上下文并从$.fn中删除countrySelect函数

让我解释一下

注意,在同一文档中初始化jquery不是两次,而是三次。 及

看到了吗?他们在第56、58和5134行

现在你在打电话 在线4701

现在,当您在第4701行country select上运行此代码时所发生的情况将附加到前面加载的jquery之一,并且它可以正常工作。然后jquery被重置,countrySelect从jquery上下文中删除,因此一旦页面完全加载,您将无法使用countrySelect

解决方案

应该只有一个jquery调用,这不是强制性的,只是良好的实践,它会降低页面加载时间

将jquery加载到中的顶部或之前的某个位置,并从第5134行中删除

或 在5134之后加载countrySelect.min.js并移动InitializeLabletItems;准备好了吗

在加载所有jquery之后,只需加载countrySelect.min.js即可

仅供参考:您正在加载的所有jquery都是同一版本的v3.4.1。所以我看不出有什么具体的理由要三次加载它。如果我错了,请纠正我


希望对您有所帮助。

尝试在ajax jQuery.getScript'中添加脚本;它不会改变任何东西InitializeLabletItems这个函数在commonFunctions js中吗?如果是,则在countrySelect js之后移动此项。如果没有,则将控制台日志$country\u selector+temp\u offer\u id.countrySelect放入{在此之前检查元素是否存在。Ahmed Sunny感谢您的建议,但commonFunctions.js根本不涉及。正如我编写的countrySelct.js加载到文档的标题中,在文档末尾附近初始化EleaFletitems,因此您建议的顺序似乎得到了尊重。我将尝试使用console.loge$country\u selector+temp\u offer\u id元素你的意思是,不是吗?我在代码中手动搜索,找到了它,但是是的,我也用console.og尝试了。是的,因为它是一个动态元素,可能是原因,如果它不存在,那么它没有为此countryselect初始化,对它调用函数会产生错误,就像使用select2或datatabl一样e并调用未初始化的元素上的事件,如果该元素存在,则会作为console.log找到它:k.fn.init[inputcountry_selector75]因此,调试器显示的错误表明问题是另一个问题,即找不到函数,而不是应用它的元素。有什么想法吗?:-Lalit Sharma非常感谢,我怀疑类似的事情,我打算开始一个漫长的过程,一件一件地删除。你救了我这么长时间浪费时间。很高兴它有用。
initializeLeafletItems(<?php echo json_encode($offers); ?>); 
function show_offers(render, from_item, to_item, products_id_list, searchedGeneric, searchedMade, searchedCountries, searchedFormats, searchedCurrency, keywords_id){

    if (render == 'PCRender') {

        $.ajax({
            method:'POST',
            url: ajax_url+'frontController/addRenderScreenOffers',
            data:{  
                          [...]
            },
            dataType:'json',

            success:function(res)
            { 

                if(res['rendered_PC_screen_offers'] != 'empty'){

                    $("#offers-product tbody").append(res['rendered_PC_screen_offers']);
                    from_item = to_item + 1;
                    to_item = to_item + 10;
                    $("#show_more_button").replaceWith('[...] )">Show More</button>');

                    initializeLeafletItems(res['offers']['offers']);
        Uncaught TypeError: $(...).countrySelect is not a function
 function countrySelectTest(){

    $this->load->view('countrySelectTest');

}

function countrySelectTestresult(){

    $random = mt_rand(0,999999999);
    $res['html_text']  = '<input type="text" id="country_selector_ajax'.$random.'" name="country_selector_ajax">';
    $res['state']  = 'success';
    $res['random'] = $random;

    echo json_encode($res);
}
        <head>
        <meta charset="utf-8">
        <title>Country Select JS</title>
        <link rel="stylesheet" href="build/css/countrySelect.css">
        <link rel="stylesheet" href="build/css/demo.css">

                <link rel="stylesheet" href="<?php echo base_url('assets/css/countrySelect.css'); ?>">    
                <link rel="stylesheet" href="<?php echo base_url('assets/css/demo.css'); ?>">  

                <script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery.js"></script>
                <script type="text/javascript" src="<?php echo base_url('assets/js/countrySelect.min.js'); ?>"></script>

        </head>
        <body>
        <h1>Country Select JS</h1>
        <form>
        <div class="" id="country">
        <input id="country" type="text">
        <label for="country_selector" style="display:none;">Select a country here...</label>
        </div>

        <button type="submit" style="display:none;">Submit</button>
        </form>
                    <button type="submit"  id="local_test">Local Test</button>
                    <button type="submit"  id="ajax_test">Ajax Test</button>
        <!-- Load jQuery from CDN so can run demo immediately -->

        <script>

        $("#country").countrySelect({
        // defaultCountry: "jp",
        // onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
        // responsiveDropdown: true,
        preferredCountries: ['ca', 'gb', 'us']
        });


        </script>

        <script>
        // Make sure we don't run this until after everything else has been loaded.
        // Using the document click handler ensures that everything else is setup first,
        // which ensures we're not cheating and adding our new element before the
        // plugin attaches to form elements the first time.

        $('#local_test').on('click', function(){

        // Step 1: Create a new element from a simulated AJAX request    
        var newInput = $('<input type="text" id="country_selector_local" name="country_selector_local">');

        // Step 2: Add the new element to the page
        $('form').append(newInput);

        // Step 3: Run the plugin on the new element
        $('#country_selector_local').countrySelect({ defaultCountry: 'au' });

        // Step 4: Profit!
        });

        $('#ajax_test').on('click', function(){

                    //the URL return te same content of previous newInput
                    $.ajax({                                                                  

                        url: 'https://www.pharmacomparison.com/frontController/countrySelectTestResult/',  
                        type: "POST",                                                          
                        enctype: 'multipart/form-data',                                      
                        data: {                                                            
                            product_info_id: 'test'                                                                  
                        },  
                        method: 'Post',  
                        dataType: 'json',  

                        success: function(response) {  
                            if(response.state=='error'){                  

                                alert(response.msg);  
                            }                        

                            if(response.state=='success'){  

                                // Step 2: Add the new element to the page
                                $('form').append(response.html_text);

                                // Step 3: Run the plugin on the new element
                                $('#country_selector_ajax'+response['random']).countrySelect({ defaultCountry: 'au' });

                                // Step 4: Profit!  

                            }

                        },



                        error: function(xhr, status, error) {      
        console.log(xhr);
        console.log(status);
        console.log(error);
                            alert("The request returned an error, please alert the site administrators (" + status +").");

                        }    
                    });      
               });


        </script>


        </body>
initializeLeafletItems(<?php echo json_encode($offers); ?>);