2015-08-08 52 views
0

为什么我的循环返回3的数组长度,但回调函数searchKey(value).length返回0?获取jQuery数组的长度

 function searchKey(value) { 
     if (value.length > 0) { 
      var keys = getKeys(value);// return array string 
      var arr = []; 
      $.post('@Url.Content("~/Home/GetJsonData")', {}, function (result) { 

       $.each(eval(result.replace(/[\r\n]/, "")), function (index, item) { 
        if (item.Tag != null) { 
         for (var i = 0; i < keys.length; i++) { 

          if (item.Tag.toLowerCase().indexOf(keys[i]) > -1) { 

           arr.push({ 
            "Key": item.Key, 
            "Value": item.Tag, 
            "Tag": keys[i], 
            "Length": keys[i].length 

           }); 
           alert("arr:" + arr.length);// result: 3 
           break; 
          } 
         } 
        } 
       });     
      }, "json"); 
     } 
     alert("arr:" + arr.length);// result: 0 
     return arr; 
} 

    function getKeys($param) { 
     //some code to find 'keys' 
     return keys; 
    } 

回答

0

jquery post/get请求是异步的。你的函数发送post请求,完成,返回空数组,然后服务器的响应返回给客户端。 您可以使其同步(https://stackoverflow.com/a/5821467/5206593),但这不是个好主意,因为您的页面会很慢。