텍스트 파일의 내용을 자바스크립트 변수로 로드하려면 어떻게 해야 합니까?
제 웹 앱 http://localhost/foo.txt 루트에 텍스트 파일이 있는데 자바스크립트의 변수에 로드하고 싶습니다.그루비에서 저는 이것을 할 것입니다:
def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
자바스크립트에서 유사한 결과를 얻으려면 어떻게 해야 합니까?
XMLHttpRequest(즉, XMLHttpRequest)입니다.XML을 사용하지 않는 AJAX.
이 작업을 수행하는 정확한 방법은 사용 중인 JavaScript 프레임워크에 따라 다르지만 상호 운용성 문제를 무시하면 코드가 다음과 같이 표시됩니다.
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
그러나 일반적으로 XMLHttpRequest는 모든 플랫폼에서 사용할 수 없기 때문에 일부 조작이 이루어집니다.다시 한 번 말하지만, 가장 좋은 방법은 jQuery와 같은 AJAX 프레임워크를 사용하는 것입니다.
한 가지 추가적인 고려 사항: 이것은 foo만큼만 작동합니다.txt가 동일한 도메인에 있습니다.다른 도메인에 있는 경우 동일한 출처의 보안 정책으로 인해 결과를 읽을 수 없습니다.
제가 jquery에서 어떻게 했는지는 다음과 같습니다.
jQuery.get('http://localhost/foo.txt', function(data) {
alert(data);
});
2019년 업데이트: 가져오기 사용:
fetch('http://localhost/foo.txt')
.then(response => response.text())
.then((data) => {
console.log(data)
})
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
텍스트 파일에서 상수 문자열만 원하는 경우 JavaScript로 포함할 수 있습니다.
// This becomes the content of your foo.txt file
let text = `
My test text goes here!
`;
<script src="foo.txt"></script>
<script>
console.log(text);
</script>
파일에서 로드된 문자열은 로드된 후 JavaScript에 액세스할 수 있습니다.'(백티크) 문자는 템플릿 리터럴로 시작하고 끝납니다. 이 문자는 텍스트 블록에서 ' 및 ' 문자를 모두 허용합니다.
이 접근 방식은 로컬에서 파일을 로드하려고 할 때 잘 작동합니다. Chrome은 다음을 포함하는 URL에서 AJAX를 허용하지 않습니다.file://
계략을 꾸미다
업데이트 2020: 비동기/대기와 함께 가져오기 사용
const response = await fetch('http://localhost/foo.txt');
const data = await response.text();
console.log(data);
참고:await
에서만 사용할 수 있습니다.async
기능.더 긴 예는 다음과 같습니다.
async function loadFileAndPrintToConsole(url) {
try {
const response = await fetch(url);
const data = await response.text();
console.log(data);
} catch (err) {
console.error(err);
}
}
loadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');
이 기능은 거의 모든 브라우저에서 작동합니다.
var xhr=new XMLHttpRequest();
xhr.open("GET","https://12Me21.github.io/test.txt");
xhr.onload=function(){
console.log(xhr.responseText);
}
xhr.send();
추가로, 새로운 것이 있습니다.Fetch
API:
fetch("https://12Me21.github.io/test.txt")
.then( response => response.text() )
.then( text => console.log(text) )
한 가지 명심해야 할 것은 자바스크립트가 서버가 아닌 클라이언트에서 실행된다는 것입니다.자바스크립트에서는 서버에서 "파일을 로드"할 수 없습니다.Javascript는 서버에 요청을 보내고 서버는 요청된 파일의 내용을 다시 보냅니다.자바스크립트는 어떻게 내용을 수신합니까?그것이 콜백 기능의 목적입니다.에드워드의 경우, 즉
client.onreadystatechange = function() {
그리고 댄브의 경우, 그것은.
function(data) {
이 기능은 데이터가 도착할 때마다 호출됩니다.jQuery 버전은 암묵적으로 Ajax를 사용하며 라이브러리에 코드를 캡슐화하여 코딩을 쉽게 합니다.
jQuery로 할 때jQuery.get
예: 예: 예: 예를 들어.
jQuery.get("foo.txt", undefined, function(data) {
alert(data);
}, "html").done(function() {
alert("second success");
}).fail(function(jqXHR, textStatus) {
alert(textStatus);
}).always(function() {
alert("finished");
});
당신은 사용할 수 있습니다..load
훨씬 더 축약된 형태를 제공합니다.
$("#myelement").load("foo.txt");
.load
또한 유용한 부분 페이지를 로드할 수 있는 옵션도 제공합니다. api.jquery.com/load/ 을 참조하십시오.
<!DOCTYPE html> <html> <body id="ibody">
<script>
fetch('http://localhost/myFolder/myFile.txt')
.then(response => response.text())
.then((data) => {ibody.innerHTML= data})
// data is the variable you want
</script> </body> </html>
언급URL : https://stackoverflow.com/questions/196498/how-do-i-load-the-contents-of-a-text-file-into-a-javascript-variable
'prosource' 카테고리의 다른 글
Powershell에서 유형 [System]을(를) 찾을 수 없습니다.창문들.Forms.KeyEventHandler] (0) | 2023.08.11 |
---|---|
CakePHP - 마지막 쿼리 실행 가져오기 (0) | 2023.08.06 |
문자열에서 동일한 각 인수에 대한 변수를 지정해야 합니까?포맷? (0) | 2023.08.06 |
jQuery를 사용하여 입력을 읽기 전용으로 만들려면 어떻게 해야 합니까? (0) | 2023.08.06 |
mysql에서 UPDATE를 수행하는 동안 여러 행에서 고유한 값을 설정하는 방법 (0) | 2023.08.06 |