我对ajax和jsonp很新,并且在调用时从文件读取时遇到问题。代码有效。但每次我在同一个脚本中再次调用相同的函数时,它会显示“未捕获的TypeError:undefined不是函数”。如果该功能有效则不应该一直有效吗?
以下是我的代码示例
var resultAmount = 0;
start = function(teamFile, rowsInDB, ratio_Over_rows, opplastx_gp, callfunction){
//ajax ONLY calls don't return anything
(function($) {
//Connects to the json teamFile
var url = 'http://xxx.co.uk/football/'+teamFile+'.json?callback=?';
//Automatic refresh
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
if(callfunction == 'mep'){
resultCount(data, rWin, count);
resultCount(data, rDraw, count);
resultCount(data, rLose, count);
//the total of w/d/l
resultAmount = total[rWin] + total[rDraw] + total[rLose] ;
}else{}
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
}
//Adds the results w, d, l up
resultCount = function(for_data, result, count_r){
count_r = 0;
//Goes through the data
for(k in for_data){
//if equals w, d, 1
if(for_data[k].Results == result){
//Add 1
count_r++;
}else{
}
}
}
//Then I call the function start twice only one works
console.log(start('ast', 7,5,5, 'mep'));
console.log(start('ars', 7,5,5, 'mep'));
只有第一个函数运行而不是第二个函数运行' Uncaught TypeError:undefined不是函数'。当我在第一个函数运行时更改它们时,第二个函数表示' Uncaught TypeError:undefined不是函数'。
如果它有助于我的文件看起来像这样
jsonCallback([{"Brad Guzan":"yes","Jed Steer":"no","Ashley Westwood":"yes","Fabian Delph":"no","Ron Vlaar":"yes","Andreas Weimann":"yes","Gabriel Agbonlahor":"no","Nathan Baker":"yes","Leandro Bacuna":"yes","Karim El Ahmadi":"no","Christian Benteke":"no","Ciaran Clark":"no","Matthew Lowton":"yes","Ryan Bertrand":"yes","Antonio Luna":"no","Marc Albrighton":"yes","Libor Koz\u00e1k":"no","Aleksandar Tonev":"no","Yacouba Sylla":"no","Grant Holt":"yes","Joseph Bennett":"yes","Chris Herd":"no","Jordan Bowery":"no","Jores Okore":"no","Gary Gardner":"no","Daniel Johnson":"no","Nicklas Helenius":"no","Jack Grealish":"no","Janoi Donacien":"no","Callum Robinson":"no","last_gp":"lose","2nd_gp":"lose","3rd_gp":"win","4th_gp":"lose","5th_gp":"lose","Home":"home","Results":"lose"});
答案 0 :(得分:2)
我发现两个文件都有'jsonCallback'作为正在读取的文档的函数。每个jsonCallback或函数都应该是唯一的。之前发生的事情是冲突,现在它是独一无二的。
Examle:
function handleData( responseData ) {
// do what you want with the data
console.log(responseData);
}
$.ajax({
url: "hi.php",
...
success: function ( data, status, XHR ) {
handleData(data);
}
});