gpt4 book ai didi

javascript - 如何在 Codeigniter 中获取 onkeyup 事件的 Ajax 函数

转载 作者:行者123 更新时间:2023-11-30 15:15:28 24 4
gpt4 key购买 nike

VIEW 文件夹中有 2 个文件:addcustomer.phpphoneError.php

addcustomer.php

<input  type="text" id="textHint" onKeyUp="showHint(this.value)" name="phone" placeholder="1235558888">
<span id="txtHint"></span>

<script type="text/javascript" >
function showHint(str) {
var base_url = <?php echo base_url(); ?>
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};

// Get $p from phoneError.php
(xmlhttp.open("GET", "phoneError.php?p=" + str, true));
xmlhttp.send();
}
}
</script>

<input type="text" id="textHint" onKeyUp="showHint(this.value)" name="phone" placeholder="1235558888">
<span id="txtHint"></span>

phoneError.php

<?php
defined('BASEPATH') || exit('No direct script access allowed');

$p = $_REQUEST['p']; // required

$string_exp = "/^[0-9]{3}[0-9]{3}[0-9]{4}$/";


if ($p == !preg_match($string_exp, $p)) {
echo $error_message .= '<span style="color:red">Oops! The Phone you entered does not appear to be valid.</span>';
}
?>

我想在 addcustomer 表单的 onkeyup 事件中添加 Ajax 函数来检查输入的有效电话号码。我调用了 addcustomer 方法并在 Controller 中加载了 phoneError 但没有成功。我不确定我为 xmlhttp.open "GET" 输入了正确的 url。

最佳答案

好吧,如果您使用的是 Codeigniter,您应该知道它的基本结构。因此,将 php 代码放在加载 View 的同一 Controller 文件中,并将其命名为

public function phoneError(){
// your php code..
}

在html端

更改 span 的 id,因为 id 在同一页面中应该是唯一的。

替换

<span id="txtHint"></span>

有了这个

<span id="txtResult"></span>

在输入标签中删除 onKeyUp 属性。所以用这个替换

<input type="text" id="textHint" name="phone" placeholder="1235558888"> 

还有js的一些变化

所以基本上你的 View 文件是

添加客户.php

<input  type="text" id="textHint"  name="phone" placeholder="1235558888" value="">
<span id="txtResult"></span>

<script type="text/javascript" >
$(document).ready(function () {

$("#textHint").keyup(function () {
var str = $(this).val();
$.get("http://localhost/sitename/controllername/phoneError?p=" + str, function (data) {
$("#txtResult").html(data);
});
});
});
</script>

现在试试这个。

关于javascript - 如何在 Codeigniter 中获取 onkeyup 事件的 Ajax 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44534510/

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