1. 程式人生 > >Jquery通過jsonp請求方式判斷URL是否有效(URL有效性檢測)

Jquery通過jsonp請求方式判斷URL是否有效(URL有效性檢測)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>URL有效性檢測</title>
		<script src="js/jquery-1.8.3.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("#checkokornot").text("Jquery is working ...");
			});
		</script>
	</head>

	<body>
		<h1>URL有效性檢測</h1>
		<h2>Jquery通過jsonp請求方式判斷URL是否有效</h2>
		<span id="checkokornot" style="color: #008000;"></span><br/><br/>
		<input type="text" id="urlForValidate" value="https://www.baidu.com"/>
		<input type="button" id="" value="驗證URL" onclick="NetPing()"/>

		<script type="text/javascript">
			function NetPing() {
				var urlForValid = $("#urlForValidate").val();
				if(urlForValid.indexOf('http')<0){alert("URL必須以http:// 或 https://開頭!");return false;}
				
				$.ajax({
					url: urlForValid,
					type: "GET",
					timeout:3000,
					dataType: "jsonp",
					complete: function(response, textStatus) {
						if(response.status == 404) {
							alert("URL請求失敗!");
						}else if(response.status == 200){
							alert("響應狀態碼:" + response.status + "\n響應資訊: " + textStatus + "\nURL狀態正常!");
						}else {
							alert("響應狀態碼:" + response.status + "\n響應資訊: " + textStatus + "\nURL 可能失效了!");
						}
					}
				});
			}
		</script>
	</body>
</html>