简体   繁体   中英

Get Element value from Ajax response

I'm new to Jquery and Ajax calls... This is my call:

$(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?

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

using 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. This is done by adding the dataType: 'json' to your $.ajax(...) call :

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

    You can alternatively use the shortcut $.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 :

     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:

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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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