如何在CodeIgniter中通过onkeyup事件实现数字转英文单词?
Got it, let's get this working for you. Right now your frontend just syncs the input value, but we need to use AJAX to send the input number to your controller's pay_number method, then display the returned words. Here's a step-by-step solution:
1. Set Up a Route for the AJAX Endpoint
First, we need a URL that your AJAX can call to reach the pay_number method. Open application/config/routes.php and add this line (replace YourController with your actual controller name):
$route['convert-to-words'] = 'YourController/pay_number';
2. Update the Controller Method to Handle AJAX Requests
Your current pay_number function echoes the result, but we need to adjust it to accept AJAX POST data and validate input. Here's the revised code:
public function pay_number() { // Block non-AJAX requests if (!$this->input->is_ajax_request()) { show_404(); } // Get the input number from AJAX $price = $this->input->post('price'); // Validate input (make sure it's a valid number) if (!is_numeric($price) || empty($price)) { echo "Please enter a valid number"; return; } // Your existing number-to-words logic here (keep it exactly as is) $ones = array( 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "Six", 7 => "seven", 8 => "eight", 9 => "nine", 10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen" ); $tens = array( 2 => "Twenty", 3 => "Thirty", 4 => "Forty", 5 => "Fifty", 6 => "Sixty", 7 => "Seventy", 8 => "Eighty", 9 => "Ninety" ); $hundreds = array("hundred", "thousand", "million", "billion", "trillion", "quadrillion"); $price = number_format($price,2,".",","); $num_arr = explode(".",$price); $wholenum = $num_arr[0]; $decnum = $num_arr[1]; $whole_arr = array_reverse(explode(",",$wholenum)); krsort($whole_arr); $rettxt = ""; foreach($whole_arr as $key => $i) { if($i < 20) { $rettxt .= $ones[$i]; } elseif($i < 100) { $rettxt .= $tens[substr($i,0,1)]; $rettxt .= " ".$ones[substr($i,1,1)]; } else { $rettxt .= $ones[substr($i,0,1)]." ".$hundreds[0]; $rettxt .= " ".$tens[substr($i,1,1)]; $rettxt .= " ".$ones[substr($i,2,1)]; } if($key > 0) { $rettxt .= " ".$hundreds[$key]." "; } } if($decnum > 0) { $rettxt .= " and "; if($decnum < 20) { $rettxt .= $ones[$decnum]; } elseif($decnum < 100) { $rettxt .= $tens[substr($decnum,0,1)]; $rettxt .= " ".$ones[substr($decnum,1,1)]; } } // Return the cleaned-up result echo trim($rettxt); }
Key changes here:
- Checks if the request is AJAX to prevent direct access
- Pulls the
pricevalue from the POST request - Adds basic validation to handle invalid inputs
- Trims extra spaces from the final result for cleaner output
3. Modify the Frontend JavaScript to Use AJAX
Replace your existing myFunction with this code to send the input value to the controller and update the display:
<label for="name" class="field-wrapper required-field">Enter Amount of Value:</label> <?php echo form_input(['name'=>'price','id'=>'price','onkeyup'=>'myFunction()']); ?> <div class="col-lg-10"> <?php echo form_error('price',"<p class='text-danger'>","</p>");?> </div> <input type="submit" value="Convert Number to Words" name="convert"/> </div> <div class="form-group"> <fieldset> <label class="control-label" for="readOnlyInput">In Words:<br><span id="demo"></span></label> </fieldset> </div> <script> // Optional: Add debounce to avoid spamming requests on every key press let debounceTimer; function myFunction() { clearTimeout(debounceTimer); const inputVal = document.getElementById("price").value.trim(); const demoElement = document.getElementById("demo"); // Clear display if input is empty if (!inputVal) { demoElement.innerHTML = ""; return; } // Wait 300ms after last key press before sending request (reduces server load) debounceTimer = setTimeout(() => { const xhr = new XMLHttpRequest(); xhr.open("POST", "<?php echo base_url('convert-to-words'); ?>", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // Update the display with the controller's response demoElement.innerHTML = xhr.responseText; } }; // Send the input value to the controller xhr.send(`price=${encodeURIComponent(inputVal)}`); }, 300); } </script>
What's new here:
- Uses
XMLHttpRequestto send a POST request to our route - Adds a debounce (300ms delay) to avoid sending a request on every single key press (better for performance)
- Handles empty input by clearing the display
- Uses
encodeURIComponentto safely pass the input value (prevents issues with special characters)
Quick Setup Check
- Make sure the URL helper is loaded so
base_url()works. You can load it in your controller with$this->load->helper('url');, or add it toapplication/config/autoload.phpunder$autoload['helper']for global access.
That's it! Now when you type in the price input, it'll send the number to your controller, convert it to words, and show the result in the #demo span automatically.
内容的提问来源于stack exchange,提问作者Sagar Parikh

