我正在尝试将它用于我的课堂作业,我还在学习。
此脚本用于检查网站是否已关闭。
我想要实现的是使用相同的脚本并获取桌面上每个网站的状态,而不再使用脚本全部3个网站。
我添加了类,但我不知道如何让它们编写脚本。我对脚本进行了评论,因此您将更容易理解。对此有何解决方案?任何意见都将不胜感激。
<table>
<thead>
<tr>
<th style="width:250px">Website</th>
<th style="width:250px">Is it live</th>
</tr>
</thead>
<tbody>
<tr>
<td>Google</td>
<td id="website"></td> <!-- This is already working. -->
</tr>
<tr>
<td>Twitter</td>
<td id="website" mywebsite="https://Twitter.com"></td> <!-- This is what I'm trying to achive. -->
</tr>
<tr>
<td>Facebook</td>
<td id="website" mywebsite="https://Facebook.com"> <!-- This is what I'm trying to achive. -->
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
var site = 'https://google.com';
// var site = 'https://google.com';
$.ajax
({
url: site,
dataType: "jsonp",
statusCode: {
200: function (response) {
$('#website').html('yes');
console.log(response);
},
404: function (response) {
$('#website').html('no');
console.log(response);
}
}
});
</script>
答案 0 :(得分:1)
<table>
<thead>
<tr>
<th style="width:250px">Website</th>
<th style="width:250px">Is it live</th>
</tr>
</thead>
<tbody>
<tr>
<td>Google</td>
<td class="website" data-mywebsite="https://google.com"></td> <!-- This is already working. -->
</tr>
<tr>
<td>Twitter</td>
<td class="website" data-mywebsite="https://twitter.com"></td> <!-- This is what I'm trying to achive. -->
</tr>
<tr>
<td>Facebook</td>
<td class="website" data-mywebsite="https://facebook.com"> </td>
</tr>
</tbody>
</table>
$(document).ready(function(){
$(".website").each(function(){
var site = $(this).attr("data-mywebsite");
var thissr = $(this);
$.ajax
({
url: site,
dataType: "jsonp",
statusCode: {
200: function (response) {
thissr.html('yes');
},
404: function (response) {
thissr.html('no');
}
}
});
});
});
试试这段代码。这是fiddle
您需要使用类并遍历每个类来发送AJAX请求。
答案 1 :(得分:0)
如您所知,Ajax是对服务器的异步调用,
因此,如果您想在循环中执行ajax调用并希望根据您的ajax调用更新某些内容,那么您必须需要一个调用ajax的上下文,
尝试以下内容,
<table>
<thead>
<tr>
<th style="width:250px">Website</th>
<th style="width:250px">Is it live</th>
</tr>
</thead>
<tbody>
<tr>
<td>Google</td>
<td class="website" data-mywebsite="https://google.com"></td> <!-- This is already working. -->
</tr>
<tr>
<td>JQuery</td>
<td class="website" data-mywebsite="http://jquery.com/"></td> <!-- This is what I'm trying to achive. -->
</tr>
<tr>
<td>Stackoverflow</td>
<td class="website" data-mywebsite="https://stackoverflow.com/"> <!-- This is what I'm trying to achive. -->
</tr>
</tbody>
</table>
$(document).ready(function(){
$(".website").each(function(){
var site = $(this).attr("data-mywebsite");
var thissr = $(this);
$.ajax
({
url: site,
dataType: "jsonp",
context : thissr,
statusCode: {
200: function (response) {
$(this.context).html('yes');
},
404: function (response) {
$(this.context).html('no');
}
}
});
});
});