gpt4 book ai didi

javascript - 当 JavaScript 触发时禁用提交按钮

转载 作者:行者123 更新时间:2023-12-03 04:12:14 26 4
gpt4 key购买 nike

我有这个表格:

<form action = "" method = "post">
<input type = "text" name = "tbox_phone" placeholder = "phone" onkeyup="checker_phone(this.value)">
<div id = "msg"></div>
<input type = "submit" name = "button_submit" value = "submit">
</form>

checker_phone 连接到通过另一个 PHP 页面运行的 JavaScript。

脚本:

<script>
function checker_phone(val)
{
$.ajax ({
type:"POST",
url:"check_phone.php",
data:'phone='+val,
success: function(data){
$("#msg").html(data);
}
});
}
</script>

PHP 页面:

$phone = htmlentities($_POST['tbox_phone']);

$var_phone= mysqli_real_escape_string($connect,$phone);

$search= "SELECT * FROM users WHERE phone= '$var_phone' ";
$exec= mysqli_query($connect,$search);
$count = mysqli_num_rows($exec);

if($count==1) {
echo "that phone number is already registered";
}

上面的代码有效。现在我想在 php 的计数结果返回 1 时禁用提交按钮。有什么办法可以做到这一点吗?

Javascript 很好,但我更喜欢简单的脚本,而不是又长又复杂的脚本。

最佳答案

首先,我建议在这种情况下避免使用内联 JS,以便更好地维护代码其次给你的字段和按钮一些标识符

<form action = "" method = "post">
<input id="userPhone" type = "text" name = "tbox_phone" placeholder = "phone">
<div id = "msg"></div>
<input id="submitAction" type = "submit" name = "button_submit" value = "submit">
</form>

出于上述原因,请将 JS 代码分开。

<script>
$( document ).ready(function() {
// Event handler
$('body').on("keyup", '#userPhone', function () {
$('#submitAction').removeAttr('disabled'); // user is typing, reactivate the submit button
checker_phone($('#userPhone').val());
});
// Ajax handler
function checker_phone(val)
{
$.ajax ({
type:"POST",
url:"check_phone.php",
cache: false,
data:{'phone':val}, // do not include parts of sql query in your JS!!!
success: function(data){
if(data.msg){
$("#msg").html(data.msg);
}
if(!data.phoneIsUnique){
$('#submitAction').attr('disabled','disabled');
}
}
});
}
});
</script>

PHP 代码

// connecting to db
$mysqli = new mysqli(
$connectionData['DB_HOST'], // some array containing connection info
$connectionData['DB_USER'],
$connectionData['DB_PASSWORD'],
$connectionData['DB_NAME']
);
$mysqli->set_charset('utf8');

$resultData = ['msg'=>'','phoneIsUnique'=>true];

// parsing request
$phone = isset($_REQUEST['phone']) ? $_REQUEST['phone'] : '';

// avoid using 'SELECT *' to avoid unnecessary overhead
$stmt = $mysqli->prepare("SELECT `phone` FROM users WHERE phone=?");
$stmt->bind_param($phone); // never ever trust client input !!! so using bind.
$stmt->execute();
if($stmt->num_rows){
$resultData = [
'msg'=>'that phone number is already registered',
'phoneIsUnique'=>false
];
}
// using Json to bounce data back to client
echo json_encode($resultData);

关于javascript - 当 JavaScript 触发时禁用提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44279283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com