2016/11/02

jQuery - Reading and displaying the content of external file

This is a quick example of how to read and display the content of an external file.

File stored on the same server

Code



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.get("demo_test.txt", function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>

demo_test.txt

1
2
3
<%
response.write("This is some text from an external TXT file.")
%>

Result

Launching the code in a browser.


Click on the button "Send an HTTP GET request to a page and get the result back".


A window will pop up showing the content of "demo_test.txt"

--------------------------------------------------------------------------------------------------------------------------

File stored on external server

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        <!--$.get("demo_test.txt", function(data, status){    -->
        $.get("http://wei48221.neocities.org/demo_test.txt", function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>

Reference:

jQuery $.get() Method
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp

No comments:

Post a Comment