无法使用Jquery从key:value对调用单个值

时间:2017-05-15 19:24:04

标签: javascript jquery json

由于一些奇怪的原因,我无法使用JQuery从它的密钥成功调用一个值。我的语法中有错误或我做错了吗?

如果我将函数“data”输出到console.log,我会得到以下结果:

{"maxFileSize" : "10 MB", "fileList" : [{"fileName" : "FVI-500_Installation", "href" : "../Docs/FVI-500_Installation.pdf","uploadDate" : "06/14/2016","fileSize" : "1.5 MB"}]}

我的HTML和Javascript:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="randominfo"></div>

<script>

    $.getJSON('http://localhost/MISREST/helpdocs', function (data) {
  $.each( JSON.parse(data), function ( key, val ) {
    $("#randominfo").append(val.maxFileSize);

  });
    });

</script>

1 个答案:

答案 0 :(得分:4)

您的代码过于复杂。请尝试以下更改:

1)您不需要致电{ "rules": { ".read": "auth != null", ".write": "auth != null", } } ,jQuery已经为您做了这个。

2)因为你已经得到了一个对象,所以你只需要使用JSON.parse,不需要循环

3)使用Promise方法,因为它允许更清晰的代码,另请参阅wildcard searching

data.maxFileSize

您的代码的最小更改如下:

$.getJSON('http://localhost/MISREST/helpdocs')
 .done(function( data ) {
     // this is the success case
     $("#randominfo").append(data.maxFileSize);
  })
 .fail(function() {
     // this is the error case
     console.log( "an error occured" );
  })
 .always(function() {
     // as the name implies, this is always executed once the request returned
     // regardless of its state. Often you won't need this.
     console.log( "the request was completed" );
  });