简体   繁体   English

Js如何调用函数并从另一个文件传递参数

[英]Js how call function and pass params from another file

I'm trying to make a main file in js with some functions. 我正在尝试使用一些功能在js中创建主文件。 I want to access geturl function from another js file inside my ajax call to post in my url. 我想从我的ajax调用中的另一个js文件访问geturl函数以发布到我的URL中。 I did like this Ajax File: 我确实喜欢这个Ajax文件:

**<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript">
(() => {
        'use strict'
$.ajax({
            url: getUrl('index','postData'),
            dataType: 'json',
                // query string parameters to append
                data: {
                  id: getId(),
              },
              type: "POST",
              success: (data) => {
                // success! we got the data!
                let card_markup = ''
                data.forEach((post) => {
                    card_markup += card(post);
                })
                $('.js-post').append(card_markup);
            }
        })
})()**

main file 主文件

**$( document ).ready(function() {

    'use strict'

    $('.back').click(function() { history.go(-1); });

    function getUrl (ctlr, act) {
        var baseurl = 'http://localhost:5002/';  
        return baseurl+'/'+ctlr+'/'+act;
    }

    function getId ()
    {
        var url = $(location).attr('href');
        var parts = url.split("/");
        var last_part = parts[parts.length-1];
        return last_part;
    }

});**

I got this error: 24781:143 Uncaught ReferenceError: getUrl is not defined at 24781:143 at 24781:184 我收到此错误:24781:143 Uncaught ReferenceError:在24781:184处24781:143处未定义getUrl

What is the best way to do this?? 做这个的最好方式是什么?? thanks in advance! 提前致谢!

Your function should be outside of dom ready function, to be accessible in other JS file: 您的函数应该在dom ready函数之外,以便可以在其他JS文件中访问:

// Should be outside dom ready scope
function getUrl (ctlr, act) {
    var baseurl = 'http://localhost:5002/';  
    return baseurl+'/'+ctlr+'/'+act;
}

function getId ()
{
    var url = $(location).attr('href');
    var parts = url.split("/");
    var last_part = parts[parts.length-1];
    return last_part;
}

$( document ).ready(function() { // <--- Start scope of DOM ready

    'use strict'

    $('.back').click(function() { history.go(-1); });

    // function inside here won't be accessible 
});  // <--- End scope of DOM ready

For instance: 例如:

function test_function() {
   function inner_scope() {
    // some definition
   }
}

inner_scope(); // will give Uncaught ReferenceError

Understanding Javascript Scope will help you understanding scope in JS. 了解Javascript范围将帮助您了解JS中的范围。

getUrl and getId are entirely private to the anonymous callback you're passing into ready . getUrlgetId完全是您ready传递给匿名回调的私有对象。 If you want those functions to be accessible from outside that callback, you need to expose them in some way (for instance, by making them globals, although in general it's best to avoid globals): 如果希望从回调外部访问这些函数,则需要以某种方式公开它们(例如,通过使它们成为全局变量,尽管通常最好避免使用全局变量):

'use strict'

$( document ).ready(function() {
    $('.back').click(function() { history.go(-1); });
});

function getId ()
{
    var url = $(location).attr('href');
    var parts = url.split("/");
    var last_part = parts[parts.length-1];
    return last_part;
}

function getUrl (ctlr, act) {
    var baseurl = 'http://localhost:5002/';  
    return baseurl+'/'+ctlr+'/'+act;
}

(Note I also moved the 'use strict' outside it so that getUrl and getId would still be in strict mode.) (请注意,我还将'use strict'移到了它'use strict'外面,以便getUrlgetId仍处于严格模式。)

If you're doing this a lot, you might look into using modules via RequireJS, Webpack, or any of several others, so you don't have to create a bunch of global variables. 如果您经常这样做,则可以考虑通过RequireJS,Webpack或其他几种方法使用模块,因此不必创建一堆全局变量。 (Native JavaScript modules support is available in cutting edge browsers, but you probably need to support ones that don't have it yet.) 最先进的浏览器提供了对本机JavaScript模块的支持,但您可能需要支持尚不支持的模块。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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