如何在jquery中从外部文件中获取json数据

时间:2016-10-24 06:55:45

标签: json

我想从外部json文件中获取所有数据并在控制台中打印,但它不是将数据提取到控制台。任何人都可以帮我解决这个问题。

{
"data": 
    {
        "slug": "allsopp-allsopp",
        "id": 401,
        "imageToken": "d045e18526f988cceb63b08e71180fb6595d9f27",
        "name": "Allsopp & Allsopp",
        "location": "Dubai",
        "description": "Allsopp & Allsopp is a family founded property services company operating a traditional UK estate agency model in the United Arab Emirates (UAE). Our mandate is to deliver levels of customer care well above prevailing industry benchmarks, in a rapid and result oriented fashion which adheres strictly to the regulatory framework now governing the local property market. Consequently the staff we employ are expected to follow a business methodology which demands exceptional honesty, a stringent code of business conduct and total transparency to the client. The key objective at Allsopp & Allsopp is to be an all embracing property service centre that caters to all types of property related transactions in the UAE.",
        "residentialForRentCount": 521,
        "residentialForSaleCount": 1114,
        "commercialForRentCount": 1,
        "commercialForSaleCount": 0,
        "commercialTotalCount": 1,
        "totalProperties": 1636,
        "agentCount": 57,
        "licenseLabel": "RERA",
        "licenseNumber": "1815",
        "phone": "+971 4 429 4444",
        "links": {
            "self": "/en/broker/allsopp-allsopp-401",
            "logo": "https://www.propertyfinder.ae/images/pf_broker/logo/d045e18526f988cceb63b08e71180fb6595d9f27/desktop",
            "logo2x": "https://www.propertyfinder.ae/images/pf_broker/logo/d045e18526f988cceb63b08e71180fb6595d9f27/desktop2x"
        }
   }
  

jquery代码

 $(document).ready(function () {
        $.getJSON('data.json', function(data) {
            console.log(data);
        });
    });

2 个答案:

答案 0 :(得分:1)

您可以尝试使用以下内容。

  1. 检查您的json文件是否与应用程序根文件夹一起放置。如果有任何其他路径,请在脚本中更改JSON URL路径。

  2. 在函数中添加JSON.Stringify()。

  3.   

    的console.log(JSON.stringify(数据));

答案 1 :(得分:-1)

我知道这比接受的答案更复杂,但它适用于想要使用PHP和Javascript(& jQuery)读取文件的人。

Javascript代码

$.post('readjson.php', {json_file: 'json.txt'}, function(json){
if (String(json).length > 0){
    console.log(json);
}else{
    console.log("Error Reading File");
}
});

PHP代码[readjson.php]

if (isset($_POST['json_file'])){
    $data = file_get_contents($_POST['json_file']);
    echo $data;
}
相关问题