2011-11-06 88 views
0

我在一個函數中創建了一個AJAX請求。但是,我不知道如何返回JSON結果 - 任何人都可以告訴我如何?如何在Sencha Touch中獲得服務器JSON響應?

function getData(arg1, arg2, arg3){ 

    Ext.Ajax.request({ 
     url: 'getData.php', 
     params: { 
      arg1: arg1, 
      arg2: arg2, 
      arg3: arg3 
     }, 
     method: 'POST', 
     success: function(response, opts) { 
      var jsonData = Ext.util.JSON.decode(response.responseText); 
      console.log(jsonData); <-- Can see the result here! 
     }, 
     failure: function(response, opts) { 
      console.log('server-side failure with status code ' + response.status); 
     } 
    }); 
    return /jsonData/ <-- Here is the value I want?! 

} 

回答

1

的原因,你的jsonData如果你用它在你的getData功能是不會得到任何信息 - 在成功回調回報(記住,請求是異步) - 該getData範圍已經退出。

,你可以和應該做的就是定義一個處理函數:

function handleSuccess(response, opts) 
{ 
    var jsonData = Ext.util.JSON.decode(response.responseText); 
    // use jsonData here in whatever way you please 
} 

然後定義你的getData像這樣:

function getData(arg1, arg2, arg3){ 

    Ext.Ajax.request({ 
     url: 'getData.php', 
     params: { 
      arg1: arg1, 
      arg2: arg2, 
      arg3: arg3 
     }, 
     method: 'POST', 
     success: handleSuccess, 
     failure: handleError 
    }); 
    // Note the lack of return statement. 
} 

當然,你可以用你的錯誤處理相同的:

function handleError(response, opts) 
{ 
    console.log('server-side failure with status code ' + response.status); 
} 

更新

沒有辦法爲你做這樣的事情(其中result將得到服務器的響應):

... 
var result = getData('arg1', 'arg2', 'arg3'); 
... 

可靠,還自稱的AJAX請求。如果你仔細想想 - 如果有上述可能,它將基本上成爲同步請求。

兩種方式在jsonData包含服務器響應做你的計算是:

1)做它在handleSuccess功能,並相應地調整你的代碼的其餘部分(如側沒有 - 你可以通過處理函數作爲參數在options.callbackExt.Ajax和)

2)通過常規手段讓你的服務器的請求同步(不推薦)

+0

感謝您的快速反應。是的,我理解你的意思,但我的目標是獲得從服務器返回的值,並且此值'jsonData'將用於另一個函數進行計算。我怎樣才能做到這一點? – hunteryxx

+0

@ user888022查看更新 – ZenMaster

+0

感謝ZenMaster,我真的很感謝你的解釋。有沒有機會通過使用商店來完成這種任務? – hunteryxx

相關問題