簡體   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