JavaScript提取,然后遇到innerHTML问题

时间:2018-12-20 19:55:00

标签: javascript

<script type="text/javascript">
      var radr;
      fetch('https://example.json')
      .then(response => response.json())
      .then(json => radr = JSON.stringify(json));
        document.getElementById('test').innerHTML = radr;
</script>

嗨。我只是测试了这段代码,无论我做什么,都只是在元素中插入了未定义的内容,但是当我使用控制台时,它就可以正常工作...

5 个答案:

答案 0 :(得分:1)

尝试

{
	"queryFilter": [{
		"objPolicyData": {"idAssign": "219","idPromotoria": "JA",
						  "listStatusPolicy": [{"policyStatusCode": "V"}],
						  "collectionType": {"DxN": true},
						  "listRetainerPaymentUnit": [{"idRetainer": "100","nameRetainer": "RETAINER","idPaymentUnit": "109","namePaymentUnit": "PAYMEMT UNIT"}],
						  "listFederalEntity": [{"idFederalEntity": "MEX","nameFederalEntity": "CDMX"}],
						  "listZipCode": ""
		},
		"policyDataInfo": {
			"policyNumber": "100",
			"sizeOfFullPolicyDataObject": 480,
			"unitSizeFullPolicyDataObject": "MB"
		}
	}]
}

答案 1 :(得分:1)

您只需要使用 querySelector("#id") 而不是 getElementById() 就可以了。一定会成功的。

答案 2 :(得分:0)

由于数据的获取是异步的,因此将逻辑放在最后一个HTML中。 目前尚不确定,因为html是在诺言完成之前呈现的

.then(json => {
   radr = JSON.stringify(json)
   document.getElementById('test').innerHTML = radr;
});

答案 3 :(得分:0)

<script type="text/javascript">
      var radr;
      fetch('https://example.json')
      .then(response => response.json())
      .then(json => {
         radr = JSON.stringify(json)
         document.getElementById('test').innerHTML = radr;
       });    
</script>

答案 4 :(得分:0)

使用document.onreadystatechange确保DOM元素已完全加载。

    <script type="text/javascript">
        document.onreadystatechange = function () {
          if (document.readyState === 'interactive') {
          var radr;
          fetch('https://example.json')
          .then(response => response.json())
          .then(json => {
             radr = JSON.stringify(json));
            document.getElementById('test').innerHTML = radr;
           }
          }
        }
    </script>