2017-06-14 34 views
1

我在VIEW文件夾中有兩個文件:addcustomer.phpphoneError.php如何在Codeigniter中獲取onkeyup事件的Ajax功能

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>'; 
    } 
?> 

我要添加Ajax功能到onkeyup事件addcustomer形式檢查輸入有效的電話號碼。我打電話給addcustomer方法,並在Controller中加載了phoneError,但沒有工作。我不確定我是否爲xmlhttp.open "GET"提供了正確的網址。

回答

1

那麼如果你使用Codeigniter,你應該知道它的基本結構。 在同一個控制器文件,以便把PHP代碼,加載你的觀點,並將其命名爲

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

在HTML邊跨

變化id作爲ID應該是在同一個頁面是獨一無二的。

與此

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

更換

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

在輸入標籤刪除的onkeyup ATTR。 所以用這個

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

更換並在JS

一些變化所以基本上你的視圖文件是

addCustomer.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> 

現在有了這個嘗試。

+0

是否在控制器中加載phoneError? public function phoneError(){ this-> load-> view('customer/phoneError'); } 在ht – jenii

+1

不,不需要在'public function phoneError()中加載任何視圖' –

1

你可以使用這個jQuery代碼爲你的目的。這段代碼和你想要的完全一樣。

$("#textHint").keyup(function() { 
    $.get("phoneError.php?p=" + $(this).val(), function (data) { 
     $("#txtHint").html(data); 
    }); 
}); 
+0

你需要糾正get url。讓我知道你是否需要進一步的幫助。 –

+0

沒有工作:(onKeyUp =「showHint(this.value)」我怎麼改變這個?我把phoneError.php放在視圖文件夾中與addcustomer相同是正確的url? – jenii

+0

不,你需要添加一個方法(比如說phoneError)你需要把你的代碼放在這個方法中,現在你可以像site_url +'controllerName/phoneError'那樣訪問它了 –