[英]How to alert PHP echo in Javascript
在這里,我正在驗證通過PHP在文本框中輸入的IP地址。
$('#check_ip').click(function() {
var iptext = $('#Ip_Txt').val();
$.ajax({
type : "POST",
url : "mypage.php",
data : { iptext : iptext , testconn : "yes" },
success : function(data) {
}
});
});
還有我的PHP
if(isset($_REQUEST['testconn'])){
if ( $_SERVER['REQUEST_METHOD'] == "POST" )
{
$input = $_POST['iptext '];
if (preg_match( "/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/", $input))
{
echo "Valid IP";
}
else
{
echo "Invalid IP";
}
}
}
一切正常。 但是我需要在單擊check_ip按鈕后在javascript 警報中顯示echo有效IP或無效IP。
在成功屬性中,通過ajax發送的請求完成后,您可以捕獲服務器發送的響應。 因此,在您的ajax成功中添加以下內容
success : function(data) {
alert(data);
}
內部警報中,您可以輸入所需的文字。 如果要檢查需要顯示什么消息,請在成功內部進行必要的檢查,然后給出必要的消息
success : function(data) {
if(condition)
alert('Some text');
else
alert('Some other text');
}
success: function(data) {
alert(data);
}
data
正在處理來自后端的回顯,因此:
$('#check_ip').click(function() {
var iptext = $('#Ip_Txt').val();
$.ajax({
type : "POST",
url : "mypage.php",
data : { iptext : iptext , testconn : "yes" },
success : function(data) {
alert(data);
}
});
});
$.ajax({
type : "POST",
url : "mypage.php",
data : { iptext : iptext , testconn : "yes" },
success : function(data) {
alert(data);
}
});
只需使用警報方法,將參數傳遞到警報框中
success : function(data) {
var response_string = JSON.stringify( data );
// do your substr operations here
alert( your_substring );
}
JSON.stringify將您的響應轉換為字符串。 然后,您可以對其執行任何字符串操作。
快樂的編碼:)
無需重新發明輪子。 您可以在此代碼上使用filter_var()
。 考慮以下示例:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$input_ip = $_POST['ip'];
echo filter_var($input_ip, FILTER_VALIDATE_IP) ? 'Valid IP' : 'Not a valid IP';
exit;
}
?>
<input type="text" id="ip_address" />
<button id="validate" type="button">Validate</button>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#validate').click(function(){
var ip = $('#ip_address').val();
$.ajax({
url: 'index.php', // just same page sample
type: 'POST',
data: {ip: ip},
success: function(response) {
alert(response);
}
});
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.