Home >Web Front-end >JS Tutorial >Let the callback function showResponse also take parameter code_javascript skills
function demo(){
var url="ajaxdemo.asp";
var paras = "" ;
var myAjax = new Ajax.Request(
url,
{
method : 'post',
parameters: paras,
onComplete: showResponse
});
}
function showResponse(originalRequest){
var html = originalRequest.responseText;
alert(html);
}
This is the most commonly seen ajax code after using prototype.js. Since showResponse cannot take parameters directly, it is sometimes troublesome to deal with callback functions, such as The returned html value should be dynamically inserted into an element. Today I finally thought of a way to solve this problem:
function demo(){
var url="ajaxdemo.asp";
var paras = "";
var myAjax = new Ajax.Request(
url,
{
method: 'post',
parameters: paras,
onComplete: function(originalRequest){showResponse(originalRequest,elemID)}
});
}
function showResponse(originalRequest,elemID){
var html = originalRequest.responseText;
$(elemID).innerHTML = html;
}
The anonymous function now acts as a callback function, and showResponse becomes a normal method. Once the concept is changed, the problem will be solved smoothly.
To solve this problem, you can also encapsulate these two functions into one function:
function demo(url,paras,updateElemID){
var myAjax = new Ajax.Request(
url,
{
method: 'post',
parameters: paras,
onComplete: function(originalRequest){showResponse(originalRequest,updateElemID)}
});
}
function showResponse(originalRequest,elemID){
var html = originalRequest.responseText;
$(elemID).innerHTML = html;
}
Only required Call demo(url,paras,updateElemID) to complete the ajax function. Cool. If the parameters are expanded and some action functions are added, it will be more than just updating the innerHTML of a certain element.