繁体   English   中英

使用jQuery显示JSON数据

[英]Displaying JSON Data using jQuery

我试图在我的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)
      }
    });

  });

});

我的结果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)
    }
  });
});

因为如果你没有那么表单将提交并且页面被刷新,并且来自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.
    },

代码中最令人困惑的部分是result键的使用。 最好在成功回调中使用不同的名称,因为我使用的data表示来自作为对象的ajax的响应数据。 所以我们只需要将其定位为:

var res = data.result.sectoutput.summarystats.Avg.Exempt;   

您可以使用jQuery.parseJSON() ,此方法将json转换为javascript对象,然后循环此对象并将html追加到页面。 使用服务器中的参数发送项目数组而不是对象会更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM