a标签里怎么判断WEB内部资源路径存不存在
时间: 2023-12-05 16:06:01 浏览: 27
可以使用JavaScript中的XMLHttpRequest对象或fetch API来检查资源路径是否存在。
使用XMLHttpRequest对象的示例代码如下:
```javascript
function checkUrl(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status != 404;
}
if (checkUrl('/path/to/resource')) {
console.log('Resource exists');
} else {
console.log('Resource does not exist');
}
```
使用fetch API的示例代码如下:
```javascript
function checkUrl(url) {
return fetch(url)
.then(response => {
if (response.ok) {
return true;
} else {
return false;
}
})
.catch(error => {
console.error(error);
return false;
});
}
checkUrl('/path/to/resource').then(exists => {
if (exists) {
console.log('Resource exists');
} else {
console.log('Resource does not exist');
}
});
```
上述代码均为同步检查,如需要异步检查,可使用回调函数或Promise进行异步处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)