2015-12-24 24 views
-1

我不知道如何實現getState。我想要做的是點擊更新一個字段,並在AJAX調用中返回一個狀態值。我在另一個回覆中看到了對承諾的引用,但我不明白如何使用它們。如何保存AJAX響應以備後用

function processRequest(e) { 
     if (xhr.readyState == 4 && xhr.status == 200) { 
      var response = JSON.parse(xhr.responseText); 
      var state = response.state; 
     } 
    } 
    $('#myState').on('click', function() { 
      var localState = getState(); 
      $('#location').val(localState); 
    }); 

回答

0

你需要改變變量的作用域所以這將是從出processRequest()功能的訪問。

var response = ''; 
var state = ''; 

function processRequest(e) { 
     if (xhr.readyState == 4 && xhr.status == 200) { 
      response = JSON.parse(xhr.responseText); 
      state = response.state; 
     } 
    } 
    $('#myState').on('click', function() { 
      $('#location').val(state); 
    });