【问题标题】:How we can get json array value in Ajax我们如何在 Ajax 中获取 json 数组值
【发布时间】:2015-11-21 12:13:53
【问题描述】:
$('#button').click(function(){
    $.ajax({
        url : "test2.php",
        data : $("#tab"),
        type : "GET",
        success : function(b){
                      b = eval('('+ b +')');    
                      console.log((b['t']));
                      alert(b);
                  }
    });
});

【问题讨论】:

标签: javascript php ajax html


【解决方案1】:

你不应该使用 eval()。您可以将请求的数据类型设置为 JSON 或使用 JSON.parse();

$('#button').click(function(){
    $.ajax({
        url : "test2.php",
        data : $("#tab"),
        type : "GET",
        success : function(b){
                      b = JSON.parse(b);    
                      console.log((b['t']));
                      alert(b);
                  }
    });
});

//datatype as JSON

$('#button').click(function(){
    $.ajax({
        url : "test2.php",
        data : $("#tab"),
        type : "GET",
        dataType: "json",
        success : function(b){   
                      console.log((b['t']));
                      alert(b);
                  }
    });
});

【讨论】:

    【解决方案2】:

    您可以使用“parseJSON”获取数据

    $('#button').click(function(){
        $.ajax({
            url : "test2.php",
            data : $("#tab"),
            type : "GET",
            success : function(b){
                     var obj = jQuery.parseJSON(b);
                     console.log(obj);
    
                    }
        });
    });
    

    【讨论】:

      【解决方案3】:

      由于您使用的是 Jquery,请尝试以下操作:

      $('#button').click(function(){
          $.ajax({
              url : "test2.php",
              data : $("#tab"),
              type : "GET",
              success : function(b){
                  var obj=jQuery.parseJSON(b);
                  alert(obj.<name>);
              }
          });
      });
      

      【讨论】:

      • 我在 json 中使用值
      • 在我想在下一页的 Ajax 中获得价值之后
      • 你能提供一些你的json值吗?顺便说一句,在以下代码中,obj.&lt;name&gt;&lt;name&gt; 更改为您的密钥。
      【解决方案4】:

      由于您使用的是AJAX,您可以直接将dataType设置为json,无需再次解析数据。

      $('#button').click(function(){
      $.ajax({
          url : "test2.php",
          data : $("#tab"),
          dataType : "json",
          type : "GET",
          success : function(b){
                        // b is in the JSON format, print the complete JSON
                        console.log(JSON.stringify(b));    
                        console.log(b['t']);
                        alert(b);
                    }
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2016-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多