gpt4 book ai didi

javascript - .getJSON 不会执行输入

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:49 24 4
gpt4 key购买 nike

我有 2 个部分

  • 第一部分,我想从用户那里获取位置输入。这是 .getJSON 不执行的地方。
  • 第二部分,我检查地理位置是否与浏览器兼容,如果授予权限,则执行 .getJSON。这个效果很好。

我认为 if(navigator.geolocation) 不会检查是否授予权限,只会检查地理位置是否与浏览器兼容。

第 1 节中的这一行 $.getJSON(address, function(data) 不会像第 2 节中那样执行。如果我将 `console.log(address) 放在它前面,它显示了,但在 .getJSON 范围内却没有显示。

由于功能相同,所以对发生的情况感到困惑。

$(document).ready(function() {
//GET STUFF FUNCTION
function getStuff(address) {
api = address; //**EDIT** changed to address
console.log("clicking or entering works yes");
$.getJSON(api, function(data) {
console.log("yay it works");
});
};
// SECTION 1
$("#searchForm").submit(function(e) {
var searchInput = $("#searchInput").val();
var address = "api.openweathermap.org/data/2.5/weather?q=" + searchInput + "&appid=?";

e.preventDefault();
getStuff(address);

});

$("#searchInput").keypress(function(e) {
if (e.which == 13) {
$("#searchBtn").click();
};
});

//SECTION 2
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;

var address = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid=?';

//tried to use this function for search
getStuff(address);
});

我尝试尽我所能缩小范围,但我不确定如何在 fiddle 上执行 AJAX 请求。编辑:更新https://jsfiddle.net/mq10ps5c/10/

谢谢大家,非常感谢大家的批评

最佳答案

在第 1 部分和第 2 部分中,您设置地址,然后在此 GetStuff 函数中调用 GetStuff,您不是引用地址,而是引用 api

将您的 GetStuff 函数更改为以下内容:

function getStuff(address) {
api = address == null ? "/echo/JSON/" : address;
console.log("clicking or entering works yes");
$.getJSON(api, function(data) {
console.log("yay it works");
});
};

首先检查地址是否为空,如果是则将api设置为“/echo/JSON/”,否则将api设置为address值.

关于javascript - .getJSON 不会执行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41233010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com