2017-06-13 71 views
0

我有一個存儲爲keyvalue的值。例如,在這種情況下,「12F」。我想看看它是否存在於我的JSON中。如果是這樣,我想獲取PNG值。如果沒有,只是發送一條消息回通過變量讀取和解析JSON

JSON

{ 
    "Property": "99", 
    "12F": { 
     "png": "12-74" 
    }, 
    "13F": { 
     "png": "12-74" 
    } 
} 

JQUERY

var sourceurl = '../floorplan-data.json'; 
     var thekeyvalue = $("#finalkey").text(); 
     //start ajax request 
     $.ajax({ 
      url: sourceurl, 
      //force to handle it as text 
      dataType: "text", 
      error: 
      function(){ 
       //error 
      }, 
      success: function(data) { 
       var json = $.parseJSON(data); 
       console.log(json.thekeyvalue); //having trouble here 
      } 
     }); 
+1

你爲什麼使用'dataType:「text」'? – SLaks

+2

試試'json [thekeyvalue]'。說明:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Property_Accessors – Will

+0

omg嚴重這就是它,但是當它無法找到它時,它將「undefined」發送給成功功能而不是錯誤。如果不存在,我如何觸發jquery。 – Omar

回答

0

這是你成功的功能應該如何。請檢查。

var sourceurl = '../floorplan-data.json'; 
    var thekeyvalue = $("#finalkey").text(); 
    //start ajax request 
    $.ajax({ 
     url: sourceurl, 
     //force to handle it as text 
     dataType: "text", 
     error: 
     function(){ 
      //error 
     }, 
     success: function(data) { 
      var json = $.parseJSON(data); 
      if(json["12F"]]) 
       return json["12F"].png; 
      else 
       return ""; 
     } 
    }); 
+0

似乎它不會解析「undefined」當它回來「undefined」時,我不斷收回一個錯誤,說:未捕獲TypeError:無法讀取屬性'png'的Object.success undefined – Omar

+0

嘗試catch成功函數爲我工作,但我想知道是否有更好的方法:在這裏找到:https://stackoverflow.com/questions/14782232/how-to-avoid-cannot-read-property-of-undefined-errors嘗試{ window.abc } catch(e){0} { console.log(「YO」,e) } – Omar

+0

您可以嘗試使用'if(json [「12F」]])'if if條件來檢查值是否爲'undefined'。 –