无法解析有效的JSON数据

时间:2015-06-10 15:32:50

标签: javascript json

我是JavaScript的新手,我遇到了这个奇怪的问题。 当我尝试将JSON数据解析为变量时,变量变为未定义。

我的代码:

document.getElementById('searchPlayerForm').onsubmit = searchPlayer; 
        function searchPlayer() {
            var request = new XMLHttpRequest(); 
            request.open(
                "GET", '${url}' + '/' + document.getElementById('playerId').value, true
            ); 
            request.setRequestHeader('accept', 'application/json');
            request.onload = responseAvailable; 
            request.send(); 
            return false; 
        }
        function responseAvailable() {
            switch (this.status) { 
            case 200:
alert(this.responseText); 
var playerResource = JSON.parse(this.responseText);
alert(playerResource.name);
...

第一个警报返回:

{"playerID":49,"lastName":"XXX","firstName":"Walter","address":{"street":"XXX 2","city":"Eisden","postalCode":"3630"},"mobilePhone":"xxxx/xx.xx.87","phone":"xxx/xx.xx.39","email":"xxx.xxx@live.be","birthDate":"1948-10-11","rank":"D2","highestRank":"C6","memberSince":"1981","clubChampion":"1996","function":"Materiaalmeester","captain":"","linkVttl":"#http://competitie.vttl.be/index.php?menu=6&season=15&sel=14501&result=1&category=1#","currentMember":true,"currentIndex":10,"compNo":"507823"}

第二个警报返回"未定义"。

任何人都知道这里可能出现什么问题?

提前致谢!

Diher

4 个答案:

答案 0 :(得分:3)

JSON中没有属性name

但是有一个firstName和lastName

要获取全名,请结束playerResource.firstNameplayerResource.lastName

var name = playerResource.firstName + ' ' + playerResource.lastName;
alert(name);

为了防止将来出现此类问题,您始终可以console.log(playerResource)检查实际拥有的数据。或者将其粘贴到JSONLint

答案 1 :(得分:1)

你的json中没有name属性。有lastNamefirstName但没有name

答案 2 :(得分:1)

如果格式化响应,答案就会变得明显:

{ "playerID": 49, "lastName": "XXX", "firstName": "Walter", "address": { "street": "XXX 2", "city": "Eisden", "postalCode": "3630" }, "mobilePhone": "xxxx/xx.xx.87", "phone": "xxx/xx.xx.39", "email": "xxx.xxx@live.be", "birthDate": "1948-10-11", "rank": "D2", "highestRank": "C6", "memberSince": "1981", "clubChampion": "1996", "function": "Materiaalmeester", "captain": "", "linkVttl": "#http://competitie.vttl.be/index.php?menu=6&season=15&sel=14501&result=1&category=1#", "currentMember": true, "currentIndex": 10, "compNo": "507823" }

如您所见,没有name键,因此访问playerResource.name将返回undefined

答案 3 :(得分:0)

没有$ LD_LIBRARY_PATH=. ldd -r ./exe linux-vdso.so.1 (0x00007ffcfa7c3000) libshared.so => ./libshared.so (0x00007f303a02e000) libc.so.6 => /lib64/libc.so.6 (0x0000003e26c00000) /lib64/ld-linux-x86-64.so.2 (0x0000003e26400000) undefined symbol: f (./exe) 键。因此,LD_LIBRARY_PATH=.未定义。尝试类似name的内容。