2017-06-29 69 views
-4

取水的時候我有一個json對象,我想通過調用ajax我有一個JSON對象,我想通過Ajax調用

[ { "color":"black", "productid":"1", "price":"1000" }, { 
    "color":"blue",  "productid":"2", "price":"2000" }, { 
    "color":"green", "productid":"3", "price":"3000" }, { 
    "color":"grey",  "productid":"4", "price":"4000" }, { 
    "color":"orange", "productid":"5", "price":"5000" }, { 
    "color":"purple", "productid":"6", "price":"6000" }, { 
    "color":"red",  "productid":"7", "price":"7000" }, { 
    "color":"violet", "productid":"8", "price":"8000" }, { 
    "color":"white", "productid":"9", "price":"9000" }, { 
    "color":"yellow", "productid":"10", "price":"10000" }, ] 

這是json文件,我下面寫的ajax去取。

$.ajax({url: 'products.json',   
     dataType: 'json',   
     data: 'data',   
     success: function(data, status, xhr) {    
           alert(data);   
       },   
       error: function(xhr, status, error) {    
            alert(status);   
       } 
     }); 
+0

的可能的複製[如何解析與jquery/JavaScript的JSON數據?](https://stackoverflow.com/questions/8951810/how-to-parse-json-data-with-jquery-javascript) –

回答

1

這裏是從products.json獲取JSON,也是正確的代碼你JSON是無效的語法錯誤

$.ajax({ 
 
\t \t url: 'products.json', 
 
\t \t dataType: 'json', 
 
\t \t success: function(data, status, xhr) { 
 
\t \t \t alert(data); 
 
\t \t }, 
 
\t \t error: function(xhr, status, error) { 
 
\t \t \t alert(status); 
 
\t \t } 
 
\t });

產品JSON應該是

[{ 
 
    "color": "black", 
 
    "productid": "1", 
 
    "price": "1000" 
 
}, { 
 
    "color": "blue", 
 
    "productid": "2", 
 
    "price": "2000" 
 
}, { 
 
    "color": "green", 
 
    "productid": "3", 
 
    "price": "3000" 
 
}, { 
 
    "color": "grey", 
 
    "productid": "4", 
 
    "price": "4000" 
 
}, { 
 
    "color": "orange", 
 
    "productid": "5", 
 
    "price": "5000" 
 
}, { 
 
    "color": "purple", 
 
    "productid": "6", 
 
    "price": "6000" 
 
}, { 
 
    "color": "red", 
 
    "productid": "7", 
 
    "price": "7000" 
 
}, { 
 
    "color": "violet", 
 
    "productid": "8", 
 
    "price": "8000" 
 
}, { 
 
    "color": "white", 
 
    "productid": "9", 
 
    "price": "9000" 
 
}, { 
 
    "color": "yellow", 
 
    "productid": "10", 
 
    "price": "10000" 
 
} ]