2018-05-09

【jQuery】$.ajax() 在 smarty 內注意事項

當網頁套用 smarty 時,若有用到 $.ajax() 時,要注意程式碼格式
  1.  
  2. $.ajax({ // 左大括號之後必須空白
  3. url: 'index.php', // 資料參數從這一列開始
  4. async: false,
  5. type: "POST",
  6. dataType: 'json',
  7. data: { ...
  8. ...
  9. 'DATA': JSON.stringify(aData)
  10. },
  11. success: function(obj_inf)
  12. {
  13. if(obj_inf.Code>0)
  14. {
  15. $('#form').submit();
  16. }
  17. else
  18. {
  19. alert(obj_inf.ResponseStr);
  20. }
  21. }
  22. });
  23.  

若緊接著寫會造成 smarty 編譯錯誤
  1.  
  2. // 這種寫法會造成 smarty 錯誤!!
  3. $.ajax({url: 'index.php',
  4. async: false,
  5. type: "POST",
  6. dataType: 'json',
  7. data: { ...
  8. ...
  9. 'DATA': JSON.stringify(aData)
  10. },
  11. success: function(obj_inf)
  12. {
  13. if(obj_inf.Code>0)
  14. {
  15. $('#form').submit();
  16. }
  17. else
  18. {
  19. alert(obj_inf.ResponseStr);
  20. }
  21. }
  22. });
  23.  

錯誤訊息
  1.  
  2. Fatal error: Uncaught exception 'SmartyCompilerException' with message 'Syntax Error in template mysmarty.tpl" on line xxx "$.ajax({url: 'index.php'," - Unexpected ": ", expected one of: "}" , " " ,
  3.