jQuery: Trigger AJAX Call on Input Change (Minimum 3 Characters)
Sure, here's an example of how you can achieve this using jQuery:\n\nhtml\n<input type="text" id="input" />\n\n<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>\n<script>\n let ajaxRequest = null;\n\n $('#input').on('input', function() {\n const inputValue = $(this).val();\n\n // Check if input length is equal or greater than 3\n if (inputValue.length >= 3) {\n // Abort the previous ajax request, if it exists\n if (ajaxRequest) {\n ajaxRequest.abort();\n }\n \n // Make a new ajax request\n ajaxRequest = $.ajax({\n url: 'your_api_endpoint',\n method: 'POST',\n data: { input: inputValue },\n success: function(response) {\n // Handle the successful response\n console.log(response);\n },\n error: function(error) {\n // Handle the error\n console.log(error);\n }\n });\n }\n });\n</script>\n\n\nIn this example, we listen for the input event on the input field. Whenever the user types or deletes a character, the event will be triggered. We then retrieve the value of the input field using $(this).val(). We check if the length of the input value is equal to or greater than 3.\n\nIf the condition is met, we first abort any ongoing ajax request using ajaxRequest.abort() to stop the previous request (if any). Then, we make a new ajax request using $.ajax(). You need to replace 'your_api_endpoint' with the actual endpoint URL to which you want to make the request.\n\nThe success callback function handles the successful response from the server, and the error callback function handles any errors that may occur during the ajax request.\n\nNote that you should replace 'your_api_endpoint' with the actual URL of your API endpoint, and handle the response and error accordingly.
原文地址: http://www.cveoy.top/t/topic/p6mR 著作权归作者所有。请勿转载和采集!