javascript - How do I include an Ajax call as an external file? - Stack Overflow

I have a simple Ajax call which works perfectly when I wrap it in the document ready function in a scri

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. 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. I have tried adding the external file in both the head and body of the HTML file like this without any success:

<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.

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. 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. I have tried adding the external file in both the head and body of the HTML file like this without any success:

<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.

Share Improve this question asked Sep 23, 2013 at 22:38 user2232681user2232681 8334 gold badges18 silver badges33 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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.

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

If the alert gets run that means your external java script file is being loaded. Otherwise something may be wrong with the path in your <script> tag.

You can call js methods from external files like below way.

 $.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);
        }
    });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744224008a4563917.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信