简体   繁体   English

如何将Ajax调用包含为外部文件?

[英]How do I include an Ajax call as an external file?

I have a simple Ajax call which works perfectly when I wrap it in the document ready function in a script before the closing body tag in my HTML file. 我有一个简单的Ajax调用,当我将它包装在HTML文件中的结束体标记之前的脚本中的文档就绪函数中时,它可以正常工作。 However, when I try to move the call into an external .js file, excluding script tags and the document ready function, the call does not work. 但是,当我尝试将调用移动到外部.js文件(不包括脚本标记和文档就绪函数)时,调用不起作用。 I have tried adding the external file in both the head and body of the HTML file like this without any success: 我尝试在HTML文件的头部和正文中添加外部文件,但没有成功:

<script src="includes_js/login3.js" type="text/javascript"></script>

I did not include much code here because I am not sure what might be helpful. 我在这里没有包含太多代码,因为我不确定什么可能有用。

However, when I try to move the call into an external .js file, excluding script tags and the document ready function

Try adding the document ready function to your external java script file. 尝试将文档就绪函数添加到外部java脚本文件中。

$(document).ready(function(){
 alert('worked');
 // ajax call here
});

If the alert gets run that means your external java script file is being loaded. 如果警报运行,则意味着正在加载外部Java脚本文件。 Otherwise something may be wrong with the path in your <script> tag. 否则, <script>标记中的路径可能出错。

You can call js methods from external files like below way. 您可以通过以下方式从外部文件调用js方法。

 $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: encodeURI("../CtrlName/MethodName"), // adjust your path
        async: true,
        data: JSON.stringify({ "param": _param }),
        dataType: "json",
        success: function (data) {
            console.log(data);
        },
        error: function (data) {
            console.log(data);
        }
    });

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

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