[英]Accessing json object values in JavaScript
我正在嘗試構建一個使用Flask使用REST API的WebApp。
我從我的API中成功獲取了JSON對象,但無法在HTML UI中顯示它。
考慮到我正在嘗試從JSON文件中打印userid,我只得到了錯誤部分。
有人可以指出問題所在嗎:
這是我的JS文件:
$(document).ready(function() { console.log("ready!"); $('#try-again').hide(); // on form submission ... $('form').on('submit', function() { console.log("the form has beeen submitted"); // grab values valueOne = $('input[name="location"]').val(); console.log(valueOne) $.ajax({ type: "POST", url: "/", data : { 'first': valueOne}, success: function(result) { if (!$.isEmptyObject({result})) { $('input').hide(); $('#try-again').show(); $('#result').html(result.userid[0]) $(document).ready(function() { console.log("ready!"); $('#try-again').hide(); // on form submission ... $('form').on('submit', function() { console.log("the form has beeen submitted"); // grab values valueOne = $('input[name="location"]').val(); console.log(valueOne) $.ajax({ type: "POST", url: "/", data : { 'first': valueOne}, success: function(result) { if (!$.isEmptyObject({result})) { $('input').hide(); $('#try-again').show(); $('#result').html(result.userid) $('#result').html('result.userid') } else { $('#result').html('Something went terribly wrong! Please try again.') } }, error: function(error) { console.log(error) } }); }); $('#try-again').on('click', function(){ $('input').val('').show(); $('#try-again').hide(); $('#result').html(''); }); }); } else { $('#result').html('Something went terribly wrong! Please try again.') } }, error: function(error) { console.log(error) } }); }); $('#try-again').on('click', function(){ $('input').val('').show(); $('#try-again').hide(); $('#result').html(''); }); });
我的JSON數據:
[{"case": 2005608875,
"filepath": "/x/eng/cs-data/latx/dev/20150510_uploads/wilp/perfstat_20150415_001256/node/10.95.172.19/output.data",
"datatype": "perf8",
"perfdateend": "2015-04-15T02:15:37-04:00",
"userid": "wilp",
"filename": "perfstat_20150415_001256.zip",
"version": "v8.1 ",
"perfdate": "2015-04-15T01:14:24-04:00"}]
這里有幾個問題,它們與Flask無關。
您檢查返回的JSON對象的length
。 但是,在JS對象中沒有length屬性,因此result.length
返回的undefined
不大於0。
由於使用的是jQuery,因此可以使用其isEmptyObject
函數檢查對象是否為空。
另外,在該if語句內,您要在HTML中插入文字字符串'result.userid'
,而不是返回的JSON的實際userid值。
if (!$.isEmptyObject(result)) {
...
$('#result').html(result.userid)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.