英文:
JavaScript DOM making server request
问题
当我加载页面时,如果没有以下js代码,它会运行得很完美,但是当我使用DOM创建HTML元素时,它会以某种方式使用相同页面url进行服务器请求,
let vehicles = <% - JSON.stringify(vehicles) %>;
displayVehicles();
function displayVehicles() { clearVehicles(); vehicles.forEach((vehicle) => { const anchorTag = document.createElement("a"); const img = document.createElement("img"); const p = document.createElement("p"); anchorTag.href = `/vehicles/${vehicle._id}`; anchorTag.classList.add("brand-vehicle"); img.src = vehicle.thumbnail; img.alt = "vehicle thumbnail"; p.textContent = vehicle.name; anchorTag.appendChild(img); anchorTag.appendChild(p); vehiclesList.appendChild(anchorTag); }); }
function clearVehicles() { while (vehiclesList.firstChild) { vehiclesList.removeChild(vehiclesList.firstChild); } } ```
我已经测试了当我注释掉js DOM代码时,它不会发出任何其他服务器请求
这是第一个请求 ``` GET /brands/dodge 200 2109.074 ms - 16952 ```
这是第二个请求,触发时我正在创建html DOM元素 ``` GET /brands/undefined 200 8297.877 ms - 16781 ```
<details>
<summary>英文:</summary>
When I'm loading the page without the following js code it runs perfectly, but when I'm creating the html elements using DOM it some how it makes server request with same page url,
const isHideVariants = document.querySelector("#hidevariants");
const vehiclesList = document.querySelector(".brand-vehicles-list");
let vehicles = <%- JSON.stringify(vehicles) %>;
displayVehicles();
function displayVehicles() {
clearVehicles();
vehicles.forEach((vehicle) => {
const anchorTag = document.createElement("a");
const img = document.createElement("img");
const p = document.createElement("p");
anchorTag.href = `/vehicles/${vehicle._id}`;
anchorTag.classList.add("brand-vehicle");
img.src = vehicle.thumbnail;
img.alt = "vehicle thumbnail";
p.textContent = vehicle.name;
anchorTag.appendChild(img);
anchorTag.appendChild(p);
vehiclesList.appendChild(anchorTag);
});
}
function clearVehicles() {
while (vehiclesList.firstChild) {
vehiclesList.removeChild(vehiclesList.firstChild);
}
}
I've tested the code when I comment the js DOM code then it was not making any other server requests
This is first request
GET /brands/dodge 200 2109.074 ms - 16952
this is second request which is triggered when I'm creating html DOM element
GET /brands/undefined 200 8297.877 ms - 16781
</details>
# 答案1
**得分**: 0
这是由`<img>`标签的`src`属性发送的GET请求。而`src`的值是`undefined`。这意味着在你的代码中`vehicle.thumbnail`也是`undefined`。
请参见https://stackoverflow.com/questions/14953792/how-src-attribute-of-img-tag-is-executed
<details>
<summary>英文:</summary>
This GET request was sent by the `src` attribute of `<img>` tag. And the value of `src` is `undefined`. Which means the `vehicle.thumbnail` is `undefined` in your code.
See https://stackoverflow.com/questions/14953792/how-src-attribute-of-img-tag-is-executed
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论