Some time ago, when I used the google map api function library, I found that the downloadUrl function is very useful, so I wrote one myself. When I get tired of what frameworks and what pools, I find that the simpler things are, the more suitable I am.
DownloadUrl (url, callback, data );
Parameter description:
Not to mention the url;
Callback is a callback function. When a function is called, there are two parameters: data, responseCode, data is responseText, and responseCode is status;
Data is the data to be post. This parameter can be omitted in get mode.
Usage 1: directly write the callback letter in the Parameter
DownloadUrl ('HTTP: // www.ugia.cn/wp-data/test.htm', function (data, responseCode ){
Alert (data); // process the returned data here
});
Usage 2: first define the callback function and then input
Function test (data, responseCode ){
Alert (data); // process the returned data here
}
DownloadUrl ('HTTP: // www.ugia.cn/wp-data/test.htm', test );
Source code:
Copy codeThe Code is as follows:
/**
* Download url lite
*
* @ Author: legend (legendsky@hotmail.com)
* @ Link: http://www.ugia.cn /? P = 122
* @ Version: 1.0
*
* @ Param string url
* @ Param string callback function
* @ Param string data post data
*
* @ Return void
*/
Function downloadUrl (url, callback, data)
{
// Init
Url + = url. indexOf ("? ")> 0? "&":"? ";
Url + = "random_download_url =" + Math. random ();
If (typeof data = 'undefined ')
{
Var data = null;
}
Method = data? 'Post': 'get ';
// Create XMLHttpRequest object
If (window. XMLHttpRequest)
{
Var objXMLHttpRequest = new XMLHttpRequest ();
}
Else
{
Var MSXML = ['msxml2. XMLHTTP.5.0 ', 'msxml2. XMLHTTP.4.0', 'msxml2. XMLHTTP.3.0 ', 'msxml2. xmlhttp', 'Microsoft. xmlhttp'];
For (var n = 0; n <MSXML. length; n ++)
{
Try
{
Var objXMLHttpRequest = new ActiveXObject (MSXML [n]);
Break;
}
Catch (e)
{
}
}
}
// Send request
With (objXMLHttpRequest)
{
// SetTimeouts (30*1000 *, 30 *, 30*60 );
Try
{
Open (method, url, true );
If (method = 'post ')
{
SetRequestHeader ('content-type', 'application/x-www-form-urlencoded; charset = UTF-8 ');
}
Send (data );
}
Catch (e)
{
Alert (e );
}
// On ready
Onreadystatechange = function ()
{
If (objXMLHttpRequest. readyState = 4)
{
Callback (objXMLHttpRequest. responseText, objXMLHttpRequest. status );
Delete (objXMLHttpRequest );
}
}
}
}