Home >Web Front-end >JS Tutorial >How Can I Retrieve AJAX Response Text Synchronously in Prototype.js?
Asynchronous JavaScript and XML (AJAX) Response Text Retrieval
In the context of prototype-based AJAX development, retrieving the response text poses a challenge. Consider the following code:
somefunction: function(){ var result = ""; myAjax = new Ajax.Request(postUrl, { method: 'post', postBody: postData, contentType: 'application/x-www-form-urlencoded', onComplete: function(transport){ if (200 == transport.status) { result = transport.responseText; } } }); return result; }
In this snippet, the "onComplete" function is executed asynchronously, long after the "someFunction" has completed. This results in an empty "result" variable.
To overcome this, a solution is proposed in the provided answer: introduce a callback function to the "someFunction" as a parameter. This callback will be invoked once the AJAX operation is complete.
Here's the modified code:
somefunction: function(callback){ var result = ""; myAjax = new Ajax.Request(postUrl, { method: 'post', postBody: postData, contentType: 'application/x-www-form-urlencoded', onComplete: function(transport){ if (200 == transport.status) { result = transport.responseText; callback(result); } } }); } somefunction(function(result){ alert(result); });
In this case, "someFunction" takes a callback as a parameter and calls it with the response text. In the example, the callback function displays an alert with the retrieved text. This mechanism ensures that the response text is available to subsequent functions when needed.
The above is the detailed content of How Can I Retrieve AJAX Response Text Synchronously in Prototype.js?. For more information, please follow other related articles on the PHP Chinese website!