2012-03-16 83 views
0

如何设置Ajax调用后的“价格”可变后设置变量? 这里的代码:ExtJS的:Ajax请求

   var price; 
       var idProd = data.prodotto_id; 

       var cb = function (o,s,r){ 

        price = Ext.util.JSON.decode(r.responseText).price; 
        console.log(price); 
       }; 
        Ext.Ajax.request({ 
         url : "index.php", 
         params : { 
          m : "Prodotti", 
          a : 'prod-price-byquantity', 
          idProd : idProd, 
          quantity: qta 
         }, 
         callback : cb, 
         scope : this 
        }); 


       console.log(price); 

在过去的console.log(价格)我看到的价格是不确定的

回答

-1

正如你可以看到,“价格”变量分配里面的“CB”功能,因此价格的值只能访问内部cb.You必须使用this.price =“喇嘛喇嘛”,因此价格将可以和你的类/命名空间里全球范围内修改。

然后你必须使用console.log(this.price);输出的价格。

+2

不是。在'price'变量被定义外'cb'功能,并且所有围绕给定的代码段完全访问。 – 2012-03-16 21:21:29

+1

谢谢指正刘若英。 – 2012-03-17 17:10:55

+0

我试过drfanai更正this.price,它不工作... – 2012-03-19 09:49:16

1

这是因为Ajax请求是异步的 - 您的回调函数将不会立即调用。这是怎么一回事呢:

var price; // = undefined; 
Ext.Ajax.request(); 
// The request is sent and the function immediately returns 
console.log(price); // undefined 
... 
some time passes 
... 
// Finally the request finishes and your callback function is called; 
price = Ext.util.JSON.decode(r.responseText).price; 
console.log(price); // some new value 

所以,你所得到的价格变量后Ajax调用完成。

+0

在我的代码中,我得到的回调函数内的变量内容...我想回调函数将被调用后的Ajax响应...你怎么看待这件事? – 2012-03-19 09:08:36

1

这项工作

fetchRow:function(params){ 
    var me = this; 
    var v; 
    this.fetchRowRequest(params,function(value){ 
     v = value; 
    }); 
    return v; 
} 
fetchRowRequest: function(params,callback){ 
    var me = this; 
    var record; 
    Ext.Ajax.request({ 
     url: me.proxy.api.read, 
     params: {filters:Ext.encode(params)}, 
     async:false, 
     success: function(response){ 
      var response = Ext.decode(response.responseText); 
      var row = response.rows[0]; 
      if(row){ 
       var record = Ext.create(me.model.prototype.modelName); 
       record.set(row); 
      }else{ 
       record = false; 
      } 
      callback(record); 
     } 
    }); 
}