我有這個簡單的腳本:簡單的jQuery AJAX回報
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 functs:
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();
};
}
感謝
你不能從AJAX調用返回。它不這樣工作。 –
什麼是「get」功能?你的意思是'$ .get'? – VisioN
而不是使用'JSON.parse',只需使用'$ .getJSON'。 –