繁体   English   中英

从Ajax响应获取元素值

[英]Get Element value from Ajax response

我是Jquery和Ajax调用的新手...这是我的调用:

$(document).ready(function () {
  $.ajax({
    type: "GET",
    url: "some url",
    success: function(response){
      console.log(response);
    }  
  })
});

控制台日志显示以下响应:

{"2014/08/08":[{},{"TEST":0}]}

如何将TEST的值保存到变量?

类似于var t = document.getElementById('test').value

使用JSON.parse

$(document).ready(function () {
  $.ajax({
    type: "GET",
    url: "some url",
    success: function(response){
      try{
        json = JSON.parse(response);
        test = null;
        $.each(json,function(i,item){
            test = item[1].TEST;
        });
        alert(test);//this is what you want
      }catch(e){}
    }  
  })
});
  1. 服务器的响应是json,因此处理它的最好方法是告诉jQuery期待一个json答案并将其转换为常规javascript对象。 这是通过在$.ajax(...)调用中添加dataType: 'json'来完成的:

     $.ajax({ type: "GET", url: "some url", dataType: "json", success: function(response){ console.log(response); } }) 

    您也可以使用快捷方式$.getJSON(...)

     $.getJSON("some url", function(response){ console.log(response); }); 
  2. 现在您有了一个常规的javascript对象,您可以使用其他答案提示:

     success: function(response) { console.log(response["2014/08/08"][1].TEST); // or $.each(response, function(i, itm) { console.log(itm[1].TEST); }; } 

尝试这个,

$.each(response,function(i,value){
   alert(value[1].Test);
});  

“想将TEST的值保存到变量中”请尝试以下操作:

var t = response["2014/08/08"][1].TEST;

演示

暂无
暂无

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

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