我试图将json文件(文本文件)中的值放入标签中,具体取决于单击按钮时文本框中给出的输入。
这是针对自动填充文本框的请求,但首先,我尝试获取标签上的值。
<form id="form1" runat="server">
<div>
<p>Suggestions: <span id="hint1"></span></p>
<input type="text" id="text1" onkeyup="loadVal()" />
<button type="button" onclick="loadVal()">Click</button>
<script>
function loadVal() {
try {
var str = document.getElementById("text1").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert("inside function");
var obj = JSON.parse(this.responseText);
obj = JSON.parse(obj);
if (obj[0].sl_no == str) {
for (i in obj.sl_no) {
document.getElementById("hint1").innerHTML = obj[i].sl_no;
}
}
}
xhttp.open("GET", "json_demo.txt", true);
xhttp.send();
};
} catch (err) {
alert(err.message);
}
}
</script>
</div>
</form>
JSON文本文件包含:
"[{\"sl_no\":\"305\"},{\"sl_no\":\"305\"},{\"sl_no\":\"3056\"},
{\"sl_no\":\"3057\"},{\"sl_no\":\"3305\"}]"
预期输出为305、3056、3057、3305
答案 0 :(得分:0)
建议:
请点击<script>
function loadVal()
{
try
{
var str = document.getElementById("text1").value;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "json_demo.txt", true);
xhttp.send();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
var obj = JSON.parse(this.responseText);
obj = JSON.parse(obj);
if (obj[0].sl_no == str)
{
for (i = 1; i < obj.length; i++)
{
document.getElementById("hint1").innerHTML += obj[i].sl_no + " ";
}
}
}
}
}
catch(err)
{
alert(err.message);
}
}
</script>
const input = [{"sl_no":"305"},{"sl_no":"305"},{"sl_no":"3056"},{"sl_no":"3057"},{"sl_no":"3305"}];
function loadVal() {
try {
var str = document.getElementById("text1").value;
const filteredOutput = input.filter((obj) => {
const val = Object.values(obj)[0];
return val.startsWith(str);
});
console.log(filteredOutput);
} catch (err) {}
}
<form id="form1" runat="server">
<div>
<p>Suggestions: <span id="hint1"></span></p>
<input type="text" id="text1" onkeyup="loadVal()" />
<button type="button" onclick="loadVal()">Click</button>
</div>
</form>
答案 1 :(得分:0)
您的JSON格式不正确,这就是发生错误的原因,在解析之前,我们将其设置为VALID JSON格式。
<html>
<body>
<script >
function loadVal() {
try {
var str = document.getElementById("text1").value;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "json_demo.txt", true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var obj='{ "hint":'+this.responseText.substring(1, this.responseText.length-1).replace(/\\/g,"")+'}'
var obj = JSON.parse(obj);
if (obj.hint[0].sl_no == str) {
for (i in obj.hint) {
document.getElementById("hint1").innerHTML = obj.hint[i].sl_no;
}
}
}
};
} catch (err) {
alert(err.message);
}
}
</script>
<form id="form1" runat="server">
<div>
<p>Suggestions: <span id="hint1"></span></p>
<input type="text" id="text1" onkeyup="loadVal()" />
<button type="button" onclick="loadVal()">Click</button>
</div>
</form>
</body>
</html>