gpt4 book ai didi

javascript - 在 html 中加载 JSON 文件

转载 作者:行者123 更新时间:2023-12-03 02:34:10 35 4
gpt4 key购买 nike

大家好,我在加载 json 文件时遇到问题。就像当我单击应该加载它的按钮时什么也没有发生一样。 HTML 新手,因此我们将不胜感激。这只是函数而不是整个文件!

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{fragments/layout :: layout (~{::body},'hello')}">
<body style="background-color:green;">
<div class="container">
<h1 style="font-family:verdana;"><center>ANAME</center></h1>
<input type='text' value='Input directory' id = 'input' style='width:200px;margin:0 50%;position:relative;left:-100px;'><br></br>
<input type='submit' value='Get Data!' id='demo' onClick='myFunction()' style='height:50px;width:100px;margin:0 50%;position:relative;left:-50px;'>


<script>
function myFunction() {
//---my custom validation---
var inputField = document.getElementById("input");
if (inputField.value == "" || inputField.value == "Input directory") {
return;
}

//---Loading JSON---
$.ajax({
url: "test.json",
dataType: "json",
data: {},
success: function(data){
//---Do whatever with the loaded 'data' variable;
alert('go');
},
error:function(error){
alert('Invalid');
}
});
}
</script>
</div>
</body>

</html>

最佳答案

function myFunction() {

var inputField = document.getElementById("input");
var fr = null;
if (input.files && input.files[0]) {
fr = new FileReader();
fr.onload = function() {
alert(fr.result);
};
fr.readAsText(inputField.files[0]);
}else
alert("plz select a file");

}
<input type="file" id="input"/>
<input type="button" onclick="myFunction()" value="test" />

你可以使用这个

$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data){},
error:function(error){}
});

大多数实现都会指定 getJSON 成功处理程序

$.getJSON( "test.json", function( data ) {
alert("success");
});

更多信息http://api.jquery.com/jquery.getjson/#jQuery-getJSON-url-data-success

编辑

要从输入元素加载 json 文件,您可以使用此

    function myFunction() {
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var inputField = document.getElementById("input");
var fr = null;
if (input.files && input.files[0]) {
fr = new FileReader();
fr.onload = function() {
alert(fr.result);
};
fr.readAsText(inputField.files[0]);
}
}

关于javascript - 在 html 中加载 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48604722/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com