我有一个问题。我正在尝试为项目创建一个AJAX框架(因为它们不允许使用第三方框架,如jQuery)。但是,当我在onreadystatechange函数中调用动态命名空间时,我遇到了问题。
这是样本ajax函数:
/**
* This function wraps the XMLHttpRequest function.
*
* String @param params.method - GET/POST
* String @param params.type - xml/text,
* String @param params.url - the target URL
* String @param params.onSuccess - the function to be called after a successful request
* String @param params.data - parameters that need to be passed to the target URL
* String @param params.asynchronous - true/false
*/
PTM.ajax = function(params)
{
var request = null;
var method = null;
var url = null;
var data = "client_id=" + PTM.clientId;
var asynchronous = (params.asynchronous == null) ? true : params.asynchronous;
// Instantiate the correct XML Http Request Object
var msxmls = [
"Msxml2.XMLHTTP.5.0",
"Msxml2.XMLHTTP.4.0",
"Msxml2.XMLHTTP.3.0",
"Msxml2.XMLHTTP",
"Microsoft.XMLHTTP"
];
for (var i=0; i < msxmls.length; i++)
{
try
{
request = new ActiveXObject(msxmls[i]);
}
catch (e) {}
}
if (request == null) throw new Error("Could not instantiate XMLHttpRequest");
// Response
request.onreadystatechange = function()
{
// The response is ready.
if ((request.readyState == 4) && (request.status == 200))
{
// Response Type
var response_type = (params.type == 'xml') ? request.responseXML : request.responseText;
PTM[params.onSuccess](response_type);
}
};
// HTTP Verb to be used.
method = params.method.toUpperCase();
// Data
data = (params.data == null) ? data : data + "&" + params.data;
// URL
url = (method == "GET") ? params.url + "?" + data : params.url;
request.open(method, url, asynchronous);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", data.length);
request.send(data);
};
这就是我使用上述功能的方法:
PTM.ajax({
method: "POST",
type: "txt",
url: urlTarget, // please delete this line when using actual code
onSuccess: callbackFunction,
data: "data=" + data,
asynchronous: false
});
如果我希望'callbackFunction'在另一个名称空间中怎么办?说'INIT.testCallbackFunction()'?
这部分是我遇到问题的地方。
// Response Type
var response_type = (params.type == 'xml') ? request.responseXML : request.responseText;
PTM[params.onSuccess](response_type);
}
当我将“PTM”命名空间作为参数传递时,如何使其动态化?