02-json-response.agi 848 B

1234567891011121314151617181920212223242526272829
  1. /*---
  2. title: JSON from POST fields
  3. group: Basics
  4. summary: Read POST fields as globals and answer with sendJSONResp().
  5. setup: {"request":{"method":"POST","form":{"city":"Hong Kong","days":"3"}}}
  6. ---*/
  7. /*
  8. A WebApp calls its backend with ao_module_agirun("App/script.agi", data, ...).
  9. Every field of data becomes a global variable here. Change them in the
  10. Request window (Form fields) and run again.
  11. */
  12. if (typeof city === "undefined" || city === "") {
  13. // A missing field is simply an undefined global.
  14. sendJSONResp({ error: "city is required" });
  15. exit();
  16. }
  17. var n = parseInt(days, 10) || 1;
  18. var forecast = [];
  19. for (var i = 0; i < n; i++) {
  20. forecast.push({
  21. day: i + 1,
  22. city: city,
  23. high: 24 + (i * 3) % 5,
  24. low: 18 + i % 3
  25. });
  26. }
  27. sendJSONResp({ city: city, days: n, forecast: forecast });