添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams window.alert("x,jsondata="+x); var jsondata = JSON.parse(x); document.getElementById("1").innerHTML = jsondata[0].1; document.getElementById("2").innerHTML = jsondata[0].2; document.getElementById("3").innerHTML = jsondata[0].3; document.getElementById("4").innerHTML = jsondata[0].4; document.getElementById("5").innerHTML = jsondata[0].5; document.getElementById("6").innerHTML = jsondata[0].6; document.getElementById("7").innerHTML = jsondata[0].7; document.getElementById("8").innerHTML = jsondata[0].8; document.getElementById("9").innerHTML = jsondata[0].9; xhttp.open("GET", "getData.php?q="+<?php echo $fileToAccess;?>, true); xhttp.send();

This is getData.php:

$file=$_REQUEST['q']; $myfile=file_get_contents($file); $json=json_decode($myfile); echo $json[1];

and this is how my json file looks like:

[{"str": "user2"},{"1": "","2": "","3": "","4": "","5": "","6": "","7": "","8": "","9": ""}]

I added a timer to constantly update the values of my buttons with the help of the json file. But I am getting the error at line

document.getElementById("1").innerHTML = jsondata[0].1;

You can only use dot notation for accessing a property, if the property name was a valid variable name. You cannot use numbers as variable names (i.e. var 1 = 'foo'; is not valid). Hence you have to use bracket notation. – Felix Kling Oct 26, 2017 at 1:09

You're pretty right in what you're doing. But since the key is numeric, you have to fetch it with ['1'] instead. Like this:

document.getElementById("1").innerHTML = jsondata[0]['1'];

In Javascript there's mainly two ways to get a property from an object

obj.prop
obj['prop']

Generally you can say that obj.prop will only work if the property is valid variable name (doesn't contain special characters, numeric, etc).

"But since the key is a number (of type string)" That's a bit confusing. Lets just say the key is numeric. – Felix Kling Oct 26, 2017 at 1:08 "obj.prop will only work if the key is not numeric" That's not quite right. There are many other cases where you cannot use dot notation, e.g. if the property name contains a space. You can only use dot notation if the property name is a valid variable name (or a keyword). – Felix Kling Oct 26, 2017 at 1:10 "obj.prop will only work if the key is not numeric, since JS can't recognize it." - Technically it's because the formal syntax does not allow it. – Derek 朕會功夫 Oct 26, 2017 at 1:10