如何在Webix Ajax请求中调用终止方法?附原生XHR终止示例
abort() to Terminate Webix Ajax Requests Great question! Webix's Ajax tools are built on top of the native XMLHttpRequest API, so accessing the abort() method is totally straightforward once you know where to look. Here's a breakdown of how to implement it:
1. Capture the Webix Ajax Request Object
Every Webix Ajax call (whether you use webix.ajax(), webix.ajax.get(), or webix.ajax.post()) returns a promise-like object that contains a reference to the underlying native XHR instance. First, you need to store this returned object in a variable so you can access it later.
Example of initiating a request and storing the object:
// Store the request object in a variable const ongoingRequest = webix.ajax().get("/your-api-endpoint", { filter: "active", limit: 10 });
2. Call abort() on the Native XHR Instance
The stored request object has a xhr property that points directly to the native XMLHttpRequest object. You can call abort() on this property whenever you need to terminate the in-flight request.
Example of aborting the request:
// Terminate the request ongoingRequest.xhr.abort();
3. Full Practical Example
Here's a complete scenario where you start a request with a button and abort it with another—plus safeguards to avoid errors:
let activeAjaxRequest = null; // Button to trigger the request webix.ui({ view: "button", value: "Fetch Data", click: function() { // Start the request and store the reference activeAjaxRequest = webix.ajax().get("https://jsonplaceholder.typicode.com/posts", function(response) { webix.message("Data loaded successfully!"); activeAjaxRequest = null; // Reset after request completes }).fail(function() { webix.message("Request failed or was aborted"); activeAjaxRequest = null; }); } }); // Button to abort the request webix.ui({ view: "button", value: "Abort Request", click: function() { // Check if there's an active request to abort if (activeAjaxRequest && activeAjaxRequest.xhr) { activeAjaxRequest.xhr.abort(); webix.message("Request aborted!"); } else { webix.message("No active request to abort"); } } });
Key Notes
- Always check if the request object and its
xhrproperty exist before callingabort()to avoidCannot read property 'abort' of undefinederrors. - Reset the request variable after the request completes (success or failure) so you don't try to abort a finished request later.
内容的提问来源于stack exchange,提问作者Vinod Sai

