我有这个简单的脚本:
function paginateUsers(page){
get( _config_remote_host+'/users?page='+page,function(json){
json = JSON.parse(json);
var _html = "";
var json_users;
var json_num_users;
if(json.users){
json_users = json.users;
json_num_users = json.number_of_users;
}
if(!json.users){
json_users = json;
json_num_users = 0;
}
for(i = 0; i < json_users.length; i ++){
if(i == 0){ _html += '<div class="row-fluid separator20">';}
_html += '<div class="span3 media userbox">'
+'<div class="row-fluid">'
+ '<div class="span3">'
+ ' <a class="thumbnail" href="#">'
+' <img src="jon.png" alt=""/>'
+' </a>'
+' </div>'
+'<div class="span9">'
+' <ul class="unstyled">'
+' <li><strong><a href="user.html?id='+json_users[i].id+'">'+json_users[i].first_name+'</strong></br>'+json_users[i].last_name+'</a></li>'
+' <li><h6>New york city</h6></li>'
+' <li><a class="pull-right btn btn-mini">Contact</a></li>'
+' </ul>'
+' </div>'
+' </div>'
+'</div>';
if(i%3 == 2){ _html += '</div><div class="row-fluid separator20">';}
}
$('.users-list').html(_html).hide().fadeIn(100);
//return always total users number to calculate total links number
return json_num_users;
});
}
然后我做
var n = paginateUsers(1);
alert(n)
但它总是提醒'未定义',这里真正的问题是什么?
这里的ajax调用和init函数:
function createCORSRequest(_method, _url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(_method, _url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(_method, _url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
/*END INIT FUNCTION*/
function get(_url, _callback){
var xhr = createCORSRequest('GET',_url);
if (!xhr){
throw new Error('CORS not supported');
}
$('.ajax-loading').show();
xhr.send();
/*SUCCESS -- do somenthing with data*/
xhr.onload = function(){
// process the response.
_callback(xhr.responseText);
$('.ajax-loading').hide();
};
xhr.onerror = function(e){
console.log(e);
$('.ajax-loading').show();
};
}
谢谢