gpt4 book ai didi

javascript - AJAX调用后JS未执行

转载 作者:行者123 更新时间:2023-12-01 00:16:45 24 4
gpt4 key购买 nike

我正在开发一个小型天气应用程序。在前端,我有一个搜索栏,每当用户输入内容时,我就会加载与用户输入的值匹配的城市列表,并按人口排序,限制为 10。

此功能现已运行:生成了 li 个城市的 ul

现在看来我的 app.js 被锁定在 AJAX 上,我正在尝试为每个 li 元素添加一个事件监听器 onclick 但它根本不执行。似乎它必须与异步/同步有关。

index.php

<body>
<?php require_once("config/db.php")?>
<h2>Weather</h2>
<input type="text" name="city-search" class="city-search" id="city-search">
<ul class="result f32">
...
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="scripts/app.js"></script>
</body>

app.js

const search = document.querySelector("#city-search");
const results = document.querySelector(".result");
const listCities = document.querySelectorAll(".cities-select");


// works
search.addEventListener("keyup", e =>{
let city = search.value;
if(city != ""){
loadCities(city);
}
});


// works
const loadCities = (city) => {
$.ajax({
url: "config/fetch-cities.php",
method: "GET",
async: true,
data: {
query: city
},
success: function(data){
results.innerHTML = data;
}
});
}

// does not execute
listCities.forEach(city => {
city.addEventListener("click", e =>{
console.log("hello world");
})
})

fetch.php

<?php 
require("db.php");

if(isset($_GET["query"])){
$search = $_GET["query"];
$results = $conn->prepare("SELECT * FROM cities WHERE city LIKE '{$search}%'
ORDER BY population DESC LIMIT 5");
}

$results->execute();
foreach ($results as $row) {
echo '<li class="cities-select">
<div> '.$row["city"].' </div>
<div> '.$row["country"].' </div>
</li>';
}
?>

最佳答案

据我所知,您在 .cities-select 存在之前调用 addEventListener (您加载页面 -> 尝试循环 .cities-选择 但它不存在)。设置 .innerHTML 后,您需要在 $.Ajax#success 函数中添加事件监听器。

const search = document.querySelector("#city-search");
const results = document.querySelector(".result");

// works
search.addEventListener("keyup", e =>{
let city = search.value;
if(city != ""){
loadCities(city);
}
});


// works
const loadCities = (city) => {
$.ajax({
url: "config/fetch-cities.php",
method: "GET",
async: true,
data: {
query: city
},
success: function(data){
results.innerHTML = data;
const cities = document.querySelectorAll(".cities-select");
cities.forEach(city => {
city.addEventListener("click", e =>{
console.log("hello world");
})
})
}
});
}

关于javascript - AJAX调用后JS未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59707580/

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