2015-12-23 57 views
2

我是jquery的新手我有一個php返回一個json,所以我可以從jquery獲得它,但是有一個問題得到結果。從jquery解析json的問題

這裏是我的代碼:

calculate: function(me, answer, res_id, soulmates) { 
     console.log('CALCULATE: '); 
     var deferred = $.Deferred(); 
     data = { 
      'me': me, 
      'answer': answer, 
      'resid': res_id, 
     }; 
     $.ajax({ 
      url: appConfig.calculate_url, 
      type: 'post', 
      beforeSend: function() { 
       console.log('BEFORE'); 
       Site.switch_calculation_animations(); 
       console.log('AFTER'); 
       console.log(appConfig.calculate_url); 
      }, 
      data: JSON.stringify(data), 
      timeout: 15000 
     }).done(function(ans) { 
      console.log(ans); 
      console.log(ans.ok); 
      console.log(ans.combi_id); 
      console.log(ans.slug); 
      if (ans.ok == 'yes') { 
       console.log('YES'); 
       deferred.resolve(ans); 
      } 
     }).fail(function(jqXHR, textStatus, error) { 
      console.log('ERROR'); 
      Site.handle_exception('calculate', { 
       'textStatus': textStatus, 
       'error': error 
      }); 
      deferred.reject(); 
     }); 
     console.log('END CALCULATE'); 
     return deferred.promise(); 
    }, 

控制檯日誌我得到的是:

CALCULATE: 
app.js?v=35:242 BEFORE 
app.js?v=35:244 AFTER 
app.js?v=35:245 /es/test_calculate/4170/waiting/ 
app.js?v=35:266 END CALCULATE 
app.js?v=35:250 {"ok":"yes","combi_id":6059244666,"slug":"true"} 
app.js?v=35:251 undefined 
app.js?v=35:252 undefined 
app.js?v=35:253 undefined 

因此,儘管確定值是 「yes」,不進入if命令。爲什麼?我錯過了什麼?

感謝

+3

右下方'data',並正上方'timeout',加上'數據類型: 'JSON',' – adeneo

回答

0

試試這個:

}).done(function(ans) { 
     var data = $.parseJSON(ans) 
     console.log(data); 
     console.log(data.ok); 
     console.log(data.combi_id); 
     console.log(data.slug); 
     if (data.ok == 'yes') { 
      console.log('YES'); 
      deferred.resolve(data); 
     } 
+0

我的工作!謝謝 –