Ank*_*ale 12 javascript jquery json
我试图在我的HTML UI中显示我的JSON数据,JSON对象正在返回,但我无法显示该对象.
这是我的JSON对象结构:
这是我的JS文件:
$(document).ready(function() {
console.log("ready!");
// on form submission ...
$('form').on('submit', function() {
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="perfid"]').val();
valueTwo = $('input[name="hostname"]').val();
valueThree = $('input[name="iteration"]').val();
console.log(valueOne)
console.log(valueTwo)
console.log(valueThree)
$.ajax({
type: "POST",
url: "/",
datatype:'json',
data : { 'first': valueOne,'second': valueTwo,'third': valueThree},
success: function(result) {
$('#result').html(result.sectoutput.summarystats.Avg.Exempt)
},
error: function(error) {
console.log(error)
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
我的结果div中没有任何结果.
编辑:
这是我的UI上的json.stringify(result)输出:
我觉得你应该停止表单提交:
$('form').on('submit', function(e) { // <-----add arg to get the event as e.
e.preventDefault(); //<----add this to stop the form submission
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="perfid"]').val();
valueTwo = $('input[name="hostname"]').val();
valueThree = $('input[name="iteration"]').val();
console.log(valueOne)
console.log(valueTwo)
console.log(valueThree)
$.ajax({
type: "POST",
url: "/",
datatype: 'json',
data: {
'first': valueOne,
'second': valueTwo,
'third': valueThree
},
success: function(data) { //<----this confused so change it to "data"
var res = data.result.sectoutput.summarystats.Avg.Exempt;
var p = '<p><pre>'+res+'</pre></p>';
$('#result').append(p); // now append the Exempts here.
},
error: function(error) {
console.log(error)
}
});
});
Run Code Online (Sandbox Code Playgroud)
因为如果不这样做,表单将提交,页面将刷新,并且来自 ajax 的数据将不会被反映。
我想真正的问题出在这里:
success: function(data) { //<----this confused so change it to "data"
var res = data.result.sectoutput.summarystats.Avg.Exempt;
var p = '<p><pre>'+res+'</pre></p>';
$('#result').append(p); // now append the Exempts here.
},
Run Code Online (Sandbox Code Playgroud)
代码中最令人困惑的部分是result
key 的使用。最好在成功回调中有一个不同的名称,就像我使用的那样data
,它表示来自 ajax 的响应数据,它是一个对象。所以我们只需要像这样定位它:
var res = data.result.sectoutput.summarystats.Avg.Exempt;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5538 次 |
最近记录: |