简体   繁体   English

我必须单击搜索按钮两次才能从api获取数据

[英]I have to click the search button two times to get the data from api

When I click the search button for the first time it gives two errors: 当我第一次单击搜索按钮时,出现两个错误:

  1. main.js:68 GET https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/API_key/ 404 (Not Found) 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. 未捕获(承诺)SyntaxError:JSON中位置0处的标记N意外。

But when I click the search button second time the error goes away. 但是,当我第二次单击搜索按钮时,错误消失了。 so I have to click the search button two times to get the data from the API. 因此,我必须单击两次搜索按钮才能从API中获取数据。

index.html 的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 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;

        })
}

You have two asynchronous operations where the second needs to use the results of the first AJAX operation to continue: 您有两个异步操作,其中第二个需要使用第一个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);

And some lines later: 还有一些行:

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

So when you click the search button the first will fire and when it returns it will fill the lat1 variable. 因此,当您单击搜索按钮时,第一个将触发,返回时将填充lat1变量。 As this is the result of a Promise, it will fire as soon as it is fulfilled while in the meantime the main thread will contine and perform the next fetch(api) statement without waiting for the lat1 to be set. 由于这是Promise的结果,它将在其完成后立即触发,同时主线程将进行构造并执行下一个fetch(api)语句,而无需等待lat1设置。 Simply move the second AJAX call into the Promise resolution: 只需将第二个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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 jQuery .submit().ajax()必须单击两次发送按钮才能获得正确的响应 - jQuery .submit() .ajax() have to click send button two times to get the correct response 我必须单击按钮两次才能将数据发布到 api 以做出反应 - i have to click on the button twice to post data to api in react 我有一个API,我想从api响应中获取数据 - I have an API, I want to get the data from api response 为什么我需要单击两次按钮才能在组件上设置道具? - Why I need to click on button two times to set props on component? 我在 Js 中有一个包含 1 到 30 的数组集合,单击按钮时,我想从中获取第一个混洗值 - I have a collection of array in Js contains 1 to 30, on button click, i want to get the first shuffled value from it 必须点击两次以在React中做一个方法 - Have to click two times to do a method in React 我怎样才能让这个按钮有两个点击事件? - How can I make this button have two click events? jQuery-搜索按钮始终获得与首次点击事件相同的数据 - Jquery - Search button always get same data to first click event 单击按钮时将数据获取到模态,按钮具有相同的 ID - Get data to Modal on button click, with buttons that have the same ID 如何通过单击按钮显示从 api 获得的数据? - How do i display the data i got from an api through a button click?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM