【问题标题】:AJAX request from JSON document来自 JSON 文档的 AJAX 请求
【发布时间】:2019-08-25 12:20:33
【问题描述】:

我有一个引导网站,其中包含几张卡片,其中包含标题、图片和价格。我想从 JSON 文档中购买这些数据。我设法部分改编了在互联网上找到的一个脚本,但我不太了解。

我需要 JSON 来存储每张卡片的数据:

  • (card1: picture:src(/ex.png), title: Test, Price: $100),
  • (card2: 图片: src(/ex2.png), 标题:Test2, 价格: $120)。

我只做了这段代码,但只对一张卡没问题,而不是很多。

脚本:

  <script>
      function ajax_get(url, callback) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                console.log('responseText:' + xmlhttp.responseText);
                try {
                    var data = JSON.parse(xmlhttp.responseText);
                } catch(err) {
                    console.log(err.message + " in " + xmlhttp.responseText);
                    return;
                }
                callback(data);
            }
        };

        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

    ajax_get('data.json', function(data,data2) {
        document.getElementById("title", "price").innerHTML = data["title"];


        var html = "<h6>" + data["title"] + "</h6>";
        html += "<p>" + data["price"] + "</p>";  
        html += "<ul>";

        document.getElementById("title").innerHTML = html;
         document.getElementById("price").innerHTML = html;
    });
     </script>

JSON:

card1{
   "title" : "CARD1",
   "price" : "$799.55",
   "image" : src("images/item1.png")
}

card2{
   "title" : "CARD2",
   "price" : "$799.55",
   "image" : src("images/item2.png")
}

卡片截图:https://imgur.com/a/CLtyfPw

一张卡片的HTML代码:

  <div class="col-sm-3">
            <div class="card1" style="width: 16rem;">
              <img src="images/landing/item1.png" class="card-img-top" alt="">
              <div class="card-body">
                <h6 id="title"></h6>
                <p id="price">/p>
              </div>
            </div>
        </div>

谢谢!

【问题讨论】:

  • 您是否从 data.json 收到有关所有卡片的信息?
  • 不,我没有收到。

标签: javascript html json ajax


【解决方案1】:

您的代码很接近,但我将展示我使用的方法,因为它更灵活。

  1. AJAX 函数(我使用的是Promises,但您可以使用callbacks 生成结果,if 语句用于 GET 请求,else 用于其他请求)
function request(method, url, data=null) {
    return new Promise((resolve, reject)=> {
    const xhr = new XMLHttpRequest;
    xhr.timeout = 2000;
    xhr.responseType = 'json'
    xhr.onreadystatechange = (e) => {
        if(xhr.readyState === 4){
            xhr.status === 200 ? resolve(xhr.response) : reject(xhr.status)
        }
    }
    xhr.ontimeout = () => reject('timeout');
    xhr.open(method, url, true);

    if(method.toString().toLowerCase() === 'get') {
        xhr.send(data)
    } else {
        xhr.setRequestHeader('Accept','application/json');
        xhr.setRequestHeader('Content-type', 'application/json');
        xhr.send(data)
    }
    })
}
  1. 渲染结果(这里我使用async/await你可以使用,Promises ora callbacks如果你愿意)。请记住,您必须将正确的路径添加到 data.json 文件!
async function getTasks(){
    const cards = await request('GET', './data.json');
    if(cards.cards.length){
        cards.cards.forEach(element=>{
        const div = document.createElement('div');
        div.className = 'card';
        div.innerHTML = `<div class="col-sm-3">
                            <div class="card1" style="width: 16rem;">
                                <img src=${element.image} class="card-img-top" alt="">
                                <div class="card-body">
                                <h6 id="title">${element.title}</h6>
                                <p id="price">${element.price}/p>
                                </div>
                            </div>
                        </div>`;
          document.body.appendChild(div);
        })
    }
}
getTasks()
  1. 你应该改变你的json文件(替换image属性,从src("images/item2.png")images/item2.png)例如:
{
    "cards": [
    {
        "title": "TEST",
        "text": "ACADEMY",
        "image": "images/featured/item1.png"
    },
    {
        "title": "TEST2",
        "text": "ACADEMY2",
        "image": "images/featured/item2.png"
        }  
    ]
}

这是一个有效的小提琴:https://jsfiddle.net/kvpqt268/

【讨论】:

  • 我有这个错误:未捕获(承诺中)类型错误:无法在 getTasks (landing.html:633) 处读取 null 的属性“长度”
  • 这意味着您的 json 文件路径错误。如果您记录 const 卡,您有任何输出吗?
  • 我修改了你的常量卡 = await request('GET', './data.json'); to const卡=等待请求('GET','data.json');因为它在同一个文件夹中。
  • 好的,但是./data.json也表示同一个文件夹
  • 我真的不知道问题出在哪里。
猜你喜欢
  • 2017-07-16
  • 2015-04-02
  • 1970-01-01
  • 2016-08-26
  • 2018-02-22
  • 1970-01-01
  • 2015-01-05
  • 2013-04-16
  • 2011-11-29
相关资源
最近更新 更多