当前位置: 代码迷 >> JavaScript >> ashx向js中传送json数据的有关问题
  详细解决方案

ashx向js中传送json数据的有关问题

热度:226   发布时间:2013-10-04 21:41:43.0
ashx向js中传送json数据的问题!
      <script >
           var CustomersData =null;
           $.ajax({
               type: 'GET',   
               url: 'ashx/Handler.ashx',  
               dataType: 'json',  
               data: 'type=1', 
               success: function (msg) {
                   CustomersData = msg;//这里alert(CustomersData );可以取到值
               },  //成功时的处理           
               error: function (data) { alert(data); }  //失败时的处理
           });
        alert(CustomersData );//这里就是null,我想在这里取到值,求大神指点啊,我不太了解JQuery
         
       </script>

------解决方案--------------------
所谓异步ajax,就是不阻塞js主线程发起的XMLHttpRequest请求。
代码$.ajax({...})并不是马上发起异步请求,要等待当前运行的js空闲下来才会发起的。
所以,按时间线来看,alert(CustomersData)的运行要早于success中的CustomersData = msg这一句,因此CustomersData自然是null,无疑。
------解决方案--------------------
 var CustomersData =null;
           $.ajax({
               type: 'GET',   
               async: false,  /////////改为同步就没问题了
               url: 'ashx/Handler.ashx',  
               dataType: 'json',  
               data: 'type=1', 
               success: function (msg) {
                   CustomersData = msg;//这里alert(CustomersData );可以取到值
               },  //成功时的处理           
               error: function (data) { alert(data); }  //失败时的处理
           });
        alert(CustomersData );//这里就是null,我想在这里取到值,求大神指点啊,我不太了解JQuery
------解决方案--------------------
success是callback 当然有值了, 你如果希望是直接取到值,自然得同步方式了

楼上几位说得也没错啊......
------解决方案--------------------
同步请求

或者 回调函数中处理
------解决方案--------------------

var CustomersData =null;
           $.ajax({
               type: 'GET',   
               url: 'ashx/Handler.ashx',  
               dataType: 'json',  
               data: 'type=1', 
               success: function (msg) {
                   CustomersData = msg;//这里alert(CustomersData );可以取到值
               },  //成功时的处理           
               error: function (data) { alert(data); }  //失败时的处理
  相关解决方案