1

私はこの簡単なスクリプトを持っています:

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)

しかし、それは常に 'undefined' を警告します。ここでの本当の問題は何ですか?

ここでは 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();
  };
}

ありがとう

4

3 に答える 3

1

AJAX 呼び出しから戻ることはできません。これは非同期です。戻り値は、AJAX 呼び出しが完了すると、将来のある時点で実行されるコールバック関数内にあります。 paginateUsers実際には何も返しません (つまり、 を返しますundefined)。

何かを返そうとする代わりに、コールバック内のデータに関連するすべてのアクションを実行する必要があります。または、コールバック関数を渡して、完了したらそれを呼び出すことをお勧めします。

function paginateUsers(page, callback){
    get( _config_remote_host+'/users?page='+page,function(json){
        // code...
        if(typeof callback === 'function'){
            callback(json_num_users); // Instead of "return json_num_users;"
        }
    });
}

次に、これを行うことができます:

paginateUsers(1, function(result){
    // result should be the value of json_num_users
});
于 2012-05-08T20:31:06.447 に答える
0

$.get は非同期で実行されています - サーバーへの新しいリクエストを開始し、サーバー側のすべての処理が完了すると何かを返します。

しかし、あなたの paginateUser() 関数はブラウザー内で実行されており、結果を待たずにリクエストを (どこにも/サーバーにも) 送信するだけです。

于 2012-05-08T20:37:07.437 に答える
0

paginateUserの結果を返す場合、から何も返していません。これはおそらく、対応するコールバックをパラメータとして受け入れるようなメソッドを持つ (jquery 1.5 以降の) オブジェクトを defered するget必要があるはずです。$.getdone then

また、これを行うことができます

var p = $.get(....)  ( or $.post or $.ajax etc )

$.when(p).done(mydone).fail(myfail)

function mydone(data){  }
function myfail(err) {  }

編集済み:編集後、自分で ajax 呼び出しを実装し、DOM 操作に jquery を使用していることがわかります。

$.getJSONURLを受け入れてdefferedオブジェクトを返すメソッドを使用する方が良いです。使用するのがはるかに便利で、しっかりしたAPIがあります

于 2012-05-08T20:30:41.703 に答える