Let the callback function showResponse also include the parameter code _ javascript skills
Source: Internet
Author: User
Let the callback function showResponse also include the parameter code 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 application prototype. ajax code that is most often seen after js. Because showResponse cannot directly include parameters, it is troublesome to process callback functions. For example, you need to dynamically Insert the returned html value into an element. Today I finally came up with 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 acts as a callback function, while showResponse becomes a common method. After changing the concept, the problem will be solved smoothly.
To solve this problem, you can encapsulate these two functions into one:
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;
}
You only need to call demo (url, paras, updateElemID) to complete the ajax function. Great. If the parameter is extended and some action functions are added, it is not just as simple as updating the innerHTML of an element.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.