Home > Web Front-end > JS Tutorial > Let the callback function showResponse also take parameter code_javascript skills

Let the callback function showResponse also take parameter code_javascript skills

WBOY
Release: 2016-05-16 19:10:28
Original
1583 people have browsed it

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.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template