如何在Javascript中创建可重用的ajax函数
我试图创建一个函数,该函数对另一台服务器进行AJAX调用,并在回调中使用返回数据。我希望能够多次调用不同的URL,并在不同的函数中使用不同的响应 目前,它进行了2次调用,但只检索了一次。我错过了什么 如果我只给树屋打一个电话,一切都很好如何在Javascript中创建可重用的ajax函数,javascript,ajax,asynchronous,Javascript,Ajax,Asynchronous,我试图创建一个函数,该函数对另一台服务器进行AJAX调用,并在回调中使用返回数据。我希望能够多次调用不同的URL,并在不同的函数中使用不同的响应 目前,它进行了2次调用,但只检索了一次。我错过了什么 如果我只给树屋打一个电话,一切都很好 /*Tests to see if ajax is available then Creates an Ajax request. *Params: url - the api url * type - the type of request (
/*Tests to see if ajax is available then Creates an Ajax request.
*Params: url - the api url
* type - the type of request (get, post). Default is get
* callback - function to process the ajax response
*/
function makeRequest(url, type, callback) {
type = typeof type !== 'undefined' ? type : 'GET';
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function(){
try {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
//Should just return the json
var response = JSON.parse(httpRequest.responseText);
// console.log(response);
return callback(response);
} else {
alert('There was a problem with the request.');
}
}
} catch(e) {
alert('Caught Exception: ' + e.description);
}
}
httpRequest.open(type, url);
//httpRequest.setRequestHeader('Content-Type', 'application/xml');
httpRequest.send();
}
下面是我如何调用函数的
makeRequest('//teamtreehouse.com/davidendersby.json', 'GET', function(treehouseData){
console.log(treehouseData);
sortedTreehousePoints = sortObject(treehouseData.points, 'DESC');
getTotalPoints(treehouseData);
getPoints();
getTreehouseBadges(treehouseData);
});
// //Not Working
makeRequest('http://api.bf4stats.com/api/playerInfo?plat=xone&name=davetherave2010&output=json','POST', function(battlefieldData){
console.log(battlefieldData);
});
似乎正在全局命名空间中声明httpRequest。像这样使用变量:
function makeRequest(url, type, callback) {
type = typeof type !== 'undefined' ? type : 'GET';
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
...
我似乎没有发现任何问题,除了 事实上,你不止一次得到回应。 第67行是控制台。后勤战场数据;第58行是控制台 我建议您检查您的XAMPP或WAMP或Apache或您正在使用的任何服务器,并尝试和/或速记方法和 编辑 另外,由于两个请求都是异步的,所以引用完整性可能存在问题。但我对此不太确定 编辑2
我所说的引用完整性是指js环境中的引用完整性,而不是数据库引用完整性,可能链接有误导性。谢谢大家的帮助。这是一个范围问题,在函数中声明httpRequest变量可以修复该问题
我在jquery方面有一些经验,我正试图用纯javascript来推广我的知识。肯定会进入严格模式。如果您在发布帖子,为什么要通过查询字符串发送参数?为什么不使用jQuery?引用完整性与异步请求有什么关系?如果您在等待响应时重新分配或更改变量值?他没有声明你看到的变量。你知道在js中使用var和不正确使用var的区别吗?。但正如我之前所说,我不太确定。据我所知,“引用完整性”是一个与数据库相关的概念,它可能适用于我不知道的其他事情,尽管我非常怀疑。关于,httpRequest之前缺少的变量:这肯定会把事情搞砸,因为onreadystatechange处理程序将使用相同的httpRequest变量似乎存在误解,我很乐意在你编辑完你的答案后对其进行投票,并澄清你所说的引用完整性是什么意思,以避免进一步的混乱。不是每个人都会阅读这些评论。