简体   繁体   English

从Ajax响应获取元素值

[英]Get Element value from Ajax response

I'm new to Jquery and Ajax calls... This is my call: 我是Jquery和Ajax调用的新手...这是我的调用:

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

The console log show this response: 控制台日志显示以下响应:

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

How can I save the value of TEST to a variable? 如何将TEST的值保存到变量?

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

using JSON.parse 使用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. The response from the server is json, so the best way to handle it is to tell jQuery to expect a json answer and turn it into a regular javascript object. 服务器的响应是json,因此处理它的最好方法是告诉jQuery期待一个json答案并将其转换为常规javascript对象。 This is done by adding the dataType: 'json' to your $.ajax(...) call : 这是通过在$.ajax(...)调用中添加dataType: 'json'来完成的:

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

    You can alternatively use the shortcut $.getJSON(...) : 您也可以使用快捷方式$.getJSON(...)

     $.getJSON("some url", function(response){ console.log(response); }); 
  2. Now that you have a regular javascript object, you can use what other answers suggest : 现在您有了一个常规的javascript对象,您可以使用其他答案提示:

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

try this, 尝试这个,

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

"want to save the value of TEST to a variable" Try this: “想将TEST的值保存到变量中”请尝试以下操作:

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

Demo 演示

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

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