How to retrieve data using $.ajax or $.get

Asked 2 years ago, Updated 2 years ago, 96 views

When I wrote the following script in jQuery, the results were as follows:

//jQuery Description
$(".Content").load("data/test.txt");

$.get("data/test.txt", function(data,status){
    $(".Content").append(data);
}, "txt";

$.ajax({
    url: "data/test.txt"
})
.then(
    function(data){
        $(".Content").append(data);
    },
    function(){
        $(".Content").append("Failed to load");
    }
);
//txt content (character code is UTF-8)
read success
// Result
<div class="Content" > Read Successful Read Failed </div>

Based on the above results, it appears that .load successfully retrieved data, and .ajax and .get failed.
I would like to obtain data from .ajax, but how can I do that?

Thank you for your cooperation.

3/26 10:24 Add
When I checked the console with FireFox developer tool, I found the following error:

Not shaped. test.txt: 1:3
It's not plastic surgery. test.htm: 1:3

In addition, following SabaMotto's suggestion, we revised the jQuery description as follows, and the results are as follows:

//jQuery Description
$(".Content").load("data/test.txt");

$.get("data/test.txt", function(data,status){
    $(".Content").append(data);
}, "text";

$.ajax({
    url: "data/test.txt",
    dataType: "text"
})
.then(
    function(data){
        $(".Content").append(data);
    },
    function(){
        $(".Content").append("Failed to load");
    }
);
// Result
<div class="Content" > Read Successfully Read Successfully </div>

Based on the above results, we believe that $.get and $.ajax have successfully retrieved the data, so we have resolved this question.

javascript jquery ajax

2022-09-30 10:45

1 Answers

The third argument I commented seems to have solved it, so I will answer it with a supplement.

$.get$.post$.ajax dataType can specify six types:

  • "xml"
  • "html"
  • "script"
  • "json"
  • "jsonp"
  • "text"
  • Default: Automatically determined from "xml", "html", "script", and "json"

If you want to retrieve plain text like this, you must explicitly specify "text" because it is not automatically determined.

Note: http://api.jquery.com/jquery.ajax/


2022-09-30 10:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.