【问题标题】:I have to click the search button two times to get the data from api我必须点击搜索按钮两次才能从 api 获取数据
【发布时间】:2019-09-10 10:28:23
【问题描述】:

当我第一次点击搜索按钮时,它给出了两个错误:

  1. main.js:68 GET https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/API_key/ 404(未找到)

  2. Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0.

但是当我第二次单击搜索按钮时,错误消失了。 所以我必须点击两次搜索按钮才能从 API 中获取数据。

index.html

<form class="searchForm" method="POST">
    <div class="form-div">
        <label for="loaction">Enter a location</label>
        <input type="text" class="searchForm-input" id="loaction" placeholder="Location">
        <button type="submit">Search</button>
    </div>
</form>
<div class="echo">--</div>
<div class="location">
    <h1 class="location-timezone">Timezone</h1>
</div>
<div class="temperature">
    <div class="degree-section">
        <h2 class="temperature-degree">34</h2>

        <span>F</span>

    </div>
</div>

main.js

let lat1 = '';
let form = document.querySelector('.searchForm');
form.addEventListener('submit', handleSubmit);

function handleSubmit(event) {
    event.preventDefault();
    const input = document.querySelector('.searchForm-input').value;
    // remove whitespace from the input
    const searchQuery = input.split(' ').join('+');
    // print `searchQuery` to the console
    console.log(searchQuery);

    let geocodeURL = `https://maps.googleapis.com/maps/api/geocode/json? 
        address=${searchQuery}&key=api_key`;

    fetch(geocodeURL)
        .then(response => {
            return response.json();
        })
        .then(data => {

            let max = data.results[0].geometry.location;
            console.log(max);

            let max1 = max.lat + ',' + max.lng;
            console.log(max1);
            lat1 = max1;
            console.log(lat1);
        })
    console.log(geocodeURL);


    let temperatureDegree = document.querySelector('.temperature-degree');
    let locationTimezone = document.querySelector('.location-timezone');
    let echos = document.querySelector('.echo');
    echos.textContent = searchQuery;

    const proxy = 'https://cors-anywhere.herokuapp.com/';
    const api =
        `${proxy}https://api.darksky.net/forecast/aki_key/${lat1}`;

    fetch(api)
        .then(response => {
            return response.json();
        })
        .then(data => {
            console.log(data);
            const {temperature} = data.currently;
            temperatureDegree.textContent = temperature;

            locationTimezone.textContent = data.timezone;

        })
}

【问题讨论】:

    标签: javascript html weather-api


    【解决方案1】:

    您有两个异步操作,其中第二个操作需要使用第一个 AJAX 操作的结果才能继续:

    fetch(geocodeURL)
            .then(response => {
                return response.json();
            })
            .then(data => {
    
              let max = data.results[0].geometry.location;
              console.log(max);
    
              let max1 = max.lat+',' + max.lng;
              console.log(max1);
               lat1 = max1; <-- lat1 is used in second AJAX call
              console.log(lat1);
            })
        console.log(geocodeURL);
    

    还有几行:

            const proxy = 'https://cors-anywhere.herokuapp.com/';
            const api = 
            `${proxy}https://api.darksky.net/forecast/aki_key/${lat1}`; // <-- lat1 will be undefined
    

    因此,当您单击搜索按钮时,第一个将触发,当它返回时,它将填充 lat1 变量。由于这是 Promise 的结果,它会在它完成后立即触发,同时主线程将继续执行下一个 fetch(api) 语句,而无需等待设置 lat1。只需将第二个 AJAX 调用移到 Promise 解析中即可:

    event.preventDefault();
    const input = document.querySelector('.searchForm-input').value;
    // remove whitespace from the input
    const searchQuery = input.split(' ').join('+');
    // print `searchQuery` to the console
    console.log(searchQuery);
    
    let geocodeURL = `https://maps.googleapis.com/maps/api/geocode/json? 
    address=${searchQuery}&key=api_key`;
    
    fetch(geocodeURL)
                .then(response => {
                    return response.json();
                })
                .then(data => {
    
                    let max = data.results[0].geometry.location;
                    console.log(max);
    
                    let max1 = max.lat+',' + max.lng;
                    console.log(max1);
                    lat1 = max1;
                    console.log(lat1);
    
                    let temperatureDegree = document.querySelector('.temperature- 
                     degree');
                    let locationTimezone = document.querySelector('.location-timezone');
                    let echos = document.querySelector('.echo');
                    echos.textContent = searchQuery;
    
                    const proxy = 'https://cors-anywhere.herokuapp.com/';
                    const api = 
                    `${proxy}https://api.darksky.net/forecast/aki_key/${lat1}`;
    
                    fetch(api)
                        .then(response => {
                            return response.json();
                        })
                        .then(data => {
                            console.log(data);
                            const {temperature} = data.currently;
                            temperatureDegree.textContent = temperature;
    
                            locationTimezone.textContent = data.timezone;
    
                        })
                    }
                })
    console.log(geocodeURL);
    

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      相关资源
      最近更新 更多