JavaScript Ping 服务器
对于 ping URL,如果该站点有效或处于活动状态,我们将收到来自服务器的消息。如果服务器判断 URL 正在播放,它将满足条件语句。
基本驱动包括一个 ajax
代码边界,它将定义请求的配置。让我们直接检查一个例子来掌握这个概念。
在 JavaScript 中使用 Ajax
来 Ping 一个 URL
我们将使用 input 元素输入用户首选的 URL,在提交之后,onclick
属性将调用 ping()
函数。我们将在 JavaScript 代码行中设置 URL 请求的配置。
我们不会有任何外部 if-else
语句来推断响应。相反,我们将有多个 statusCode
根据服务器的响应返回语句。
代码片段 - index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="index.js"></script>
<script type="text/javascript" src=
"https://code.jquery.com/jquery-1.7.1.min.js">
</script>
<title>Ping using JavaScript</title>
</head>
<body>
<label for="url">
URL you want to ping:
</label><br>
<input type="text" id="url"
name="url" style="margin: 10px;"><br>
<input type="submit" value="Submit"
onclick="ping()">
</body>
</html>
代码片段 - index.js
:
function ping() {
// The custom URL
var URL = $('#url').val();
var settings = {
cache: false,
dataType: 'jsonp',
async: true,
crossDomain: true,
url: URL,
method: 'GET',
// For response
statusCode: {
200: function(response) {
console.log('Status 200: Page is up!');
},
400: function(response) {
console.log('Status 400: Page is down.');
},
0: function(response) {
console.log('Status 0: Page is down.');
},
},
};
// Sends the request and observes the response
$.ajax(settings).done(function(response) {
console.log(response);
});
}
输出:
控制台以状态 200 响应该语句并表示该页面处于活动状态,并且此特定响应的标题为 pong。这是你 ping 特定 URL 以检查其有效性的方式。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。