简体   繁体   English

如何从 JSON 警告输入值(javascript)

[英]How to alert input value from JSON (javascript)

I have a problem trying to alert input values from json object.我在尝试提醒来自 json object 的输入值时遇到问题。 I get 'undefined' when i execute this code.当我执行此代码时,我得到“未定义”。 Can someone please give me some ideas, I think I tried everything.有人可以给我一些想法,我想我已经尝试了一切。 btw.顺便提一句。 I have to use JSON because it is my school project.我必须使用 JSON 因为这是我的学校项目。 Thank you!谢谢! xx xx

<script>
let arr = [];

function adduser(){
    let user = {
        name: document.getElementById("first_name").value,
        lname: document.getElementById("last_name").value,
        text: document.getElementById("txtara").value,
        email: document.getElementById("emails").value
    }

    arr.push(user);
    let json_str = JSON.stringify(arr);
    alert(json_str.name);
}
</script>

You're trying to "print" a value from string, that's not possible.您试图从字符串中“打印”一个值,这是不可能的。 If you want to convert your array to JSON and next "print" it on an alert, please try this:如果您想将您的阵列转换为 JSON 并在警报下“打印”它,请尝试以下操作:

let user={
name:document.getElementById("first_name").value,
 lname:document.getElementById("last_name").value,
 text:document.getElementById("txtara").value,
 email:document.getElementById("emails").value
}
let json = JSON.parse(user);
alert(json.name);

You can't access json the same way you access an object.您无法像访问 object 一样访问 json。 JSON is a string, you can still find user and it's name by searching through a string, but since it's your school project I honestly doubt that is the point of the lesson. JSON 是一个字符串,您仍然可以通过搜索字符串找到用户及其名称,但由于这是您的学校项目,我真的怀疑这就是本课的重点。

You probably have to to JSON.parse(arr)[0].name where 0 is first index of your array, since you push the user to it.您可能必须JSON.parse(arr)[0].name其中 0 是数组的第一个索引,因为您将用户推送到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM