2011-06-01 47 views
0

訪問JSON我有此JSON在我的要求下如何通過jQuery

$.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&current_id=" + current_id + "&standard_id=" + standard + "&professional_id=" + professional + "&premium_id=" + premium + "&quantity=" + quantity, 
     function(data) { 
      var standard_price  = data.standard_price; 
      var professional_price = data.professional_price; 
      var premium_price  = data.premium_price; 
         console.log(data); 
        $prettyCheckBox0.text(standard_price); 
        $prettyCheckBox1.text(professional_price); 
        $prettyCheckBox2.text(premium_price); 
    }); 

的問題是,data.standard_price返回undefined但在執行console.log我有這個

"{"standard_price":"included","professional_price":"add $792.00","premium_price":"add $3372.00"}" 

什麼該交易

回答

5

您需要解析JSON。將這個作爲回調的第一行:

data = $.parseJSON(data); 

或者,使用$.getJSON代替$.get或通過"json"作爲另一參數$.get

1

console.log似乎表明您有一個字符串,而不是一個實際的Javascript對象。您需要告訴jQuery將內容視爲JSON併爲您提供解析對象。最簡單的方法是使用$.getJSON,而不是$.get

$.getJSON("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&current_id=" + current_id + "&standard_id=" + standard + "&professional_id=" + professional + "&premium_id=" + premium + "&quantity=" + quantity, 
    function(data) { 
     var standard_price  = data.standard_price; 
     var professional_price = data.professional_price; 
     var premium_price  = data.premium_price; 
        console.log(data); 
       $prettyCheckBox0.text(standard_price); 
       $prettyCheckBox1.text(professional_price); 
       $prettyCheckBox2.text(premium_price); 
}); 
2

您應該使用$ .parseJSON(字符串),如下所示:

$.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&current_id=" + current_id + "&standard_id=" + standard + "&professional_id=" + professional + "&premium_id=" + premium + "&quantity=" + quantity, 
     function(data) {data = $.parseJSON(data); 
      var standard_price  = data.standard_price; 
      var professional_price = data.professional_price; 
      var premium_price  = data.premium_price; 
         console.log(data); 
        $prettyCheckBox0.text(standard_price); 
        $prettyCheckBox1.text(professional_price); 
        $prettyCheckBox2.text(premium_price); 
    }); 

另一種方法是使用$ .ajax指定在dataType: 'json'中看到http://api.jquery.com/jQuery.ajax/