Load .txt file using JQuery or Ajax

后端 未结 4 623
南笙
南笙 2020-12-02 00:07

How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn\'t. Pro JQuery explains what causes this, but it doesn\'t

4条回答
  •  一生所求
    2020-12-02 00:31

    Try this:

    HTML:

    JavaScript:

    $(function(){
        $( "#target" ).load( "pathToYourFile" );
    });
    

    In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.

    The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.

    Edit: Other examples to get the value to be manipulated

    Using $.get() function:

    $(function(){
        $.get( "pathToYourFile", function( data ) {
            var resourceContent = data; // can be a global variable too...
            // process the content...
        });
    });
    

    Using $.ajax() function:

    $(function(){
        $.ajax({
            url: "pathToYourFile",
            async: false,   // asynchronous request? (synchronous requests are discouraged...)
            cache: false,   // with this, you can force the browser to not make cache of the retrieved data
            dataType: "text",  // jQuery will infer this, but you can set explicitly
            success: function( data, textStatus, jqXHR ) {
                var resourceContent = data; // can be a global variable too...
                // process the content...
            }
        });
    });
    

    It is important to note that:

    $(function(){
        // code...
    });
    

    Is the same as:

    $(document).ready(function(){
        // code
    });
    

    And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.

提交回复
热议问题