Ajax调用以获取使用IProgress的进度。

huangapple go评论95阅读模式
英文:

Ajax call to get progress using IProgress

问题

这是您提供的代码的翻译:

  1. 我有2ajax api调用一个在一个长时间的过程中获取数据另一个使用IProgress接口获取进度值并每5秒执行一次当进入调试器时我可以看到值在ReportProgress中更新并且这个值被设置为_generateRecipeCardsStatus属性我的问题是当调用getProgress() -> GeneratePrintRecipeCardsStatus属性_generateRecipeCardsStatus始终为零我错在哪里
  2. 谢谢
  3. <script>
  4. getData();
  5. getProgress()
  6. // 长时间的过程
  7. function getData() {
  8. const token = $('input[name="__RequestVerificationToken"]').val();
  9. $.ajax({
  10. headers: {
  11. 'X-Requested-With': 'XMLHttpRequest',
  12. "X-ANTI-FORGERY-TOKEN": token
  13. },
  14. type: 'POST',
  15. url: `@Url.Action("GeneratePrintRecipeCards", "MenuPrintout")?id=` + @Model.RecipeCardLabelId + `&menuHeaderId=` + @Model.MenuHeaderId,
  16. success: function(response){
  17. console.log(response)
  18. const { errorMsg, progressValue } = response
  19. inProgressEle.hide();
  20. close.show();
  21. if (errorMsg) {
  22. toast(errorMsg, "error")
  23. }
  24. else if (progressValue > 0) {
  25. console.log("进度值:" + progressValue);
  26. }
  27. else{
  28. expand.hide()
  29. collapse.hide()
  30. statusEle.text("准备就绪");
  31. completedEle.fadeIn()
  32. }
  33. }
  34. });
  35. }
  36. // 获取进度
  37. function getProgress() {
  38. setInterval(function(){
  39. $.ajax({
  40. url: '@Url.Action("GeneratePrintRecipeCardsStatus", "MenuPrintout")',
  41. type: "GET",
  42. success: function (response) {
  43. console.log(response)
  44. $('#lblStatus').text(response)
  45. }
  46. })
  47. }, 5000)
  48. }
  49. </script>
  50. // 控制器
  51. public class MenuPrintoutController : BaseController
  52. {
  53. private readonly IMenuLabelService _menuLabelService;
  54. private int _generateRecipeCardsStatus;
  55. private Progress<int> _progress;
  56. public MenuPrintoutController(IMenuLabelService menuLabelService)
  57. {
  58. _menuLabelService = menuLabelService;
  59. }
  60. // 总是为零
  61. public int GeneratePrintRecipeCardsStatus()
  62. {
  63. return _generateRecipeCardsStatus;
  64. }
  65. // 更新正常
  66. private void ReportProgress(int progress)
  67. {
  68. _generateRecipeCardsStatus = progress;
  69. }
  70. [HttpPost]
  71. [ValidateAntiForgeryToken]
  72. public async Task<IActionResult> GeneratePrintRecipeCards(int id, int menuHeaderId)
  73. {
  74. try
  75. {
  76. _progress = new Progress<int>(ReportProgress);
  77. var data = await _menuLabelService.DoAsync(int menuHeaderId, _progress);
  78. TempData.Put("PrintRecipeCards", data);
  79. return Json(new { Success = true });
  80. }
  81. catch (Exception exp)
  82. {
  83. return Json(new { ErrorMsg = exp.Message });
  84. }
  85. }
  86. }
  87. // 服务
  88. public interface IMenuLabelService
  89. {
  90. Task<object> DoAsync(int menuHeaderId, IProgress<int> progress);
  91. }
  92. public class MenuLabelService : IMenuLabelService
  93. {
  94. public async Task<object> DoAsync(int menuHeaderId, IProgress<int> progress)
  95. {
  96. var menuFoodItemsList = _context.FoodItemUnits
  97. .Where(x => x.MenuSectionFoodItemUnits.Any(y => y.Menusection.MenuheaderId == menuHeaderId))
  98. .Select(x => x.Fooditem)
  99. .ToList();
  100. var menuFoodItems = new List<PrintLabel>();
  101. var donePointer = 0;
  102. foreach (var menuFoodItem in menuFoodItemsList)
  103. {
  104. menuFoodItems.Add(menuFoodItem);
  105. // ...
  106. progress.Report((int)(++donePointer / (double)menuFoodItemsList.Count * 100));
  107. donePointer++;
  108. }
  109. return menuFoodItems;
  110. }
  111. }

请注意,代码中的某些部分可能需要根据上下文和项目的具体要求进行进一步优化或调整。

英文:

I have 2 ajax api calls one fetches data in a long process and and other gets the progress value using IProgress interface and executes every 5 seconds. When hitting the debugger I can see the value updates in ReportProgress and this value gets set to _generateRecipeCardsStatus property. My issue is when calling getProgress() -> GeneratePrintRecipeCardsStatus the propety _generateRecipeCardsStatus is always zero where am I going wrong?

Thanks

  1. &lt;script&gt;
  2. getData();
  3. getProgress()
  4. // long process
  5. function getData() {
  6. const token = $(&#39;input[name=&quot;__RequestVerificationToken&quot;]&#39;).val();
  7. $.ajax({
  8. headers: {
  9. &#39;X-Requested-With&#39;: &#39;XMLHttpRequest&#39;,
  10. &quot;X-ANTI-FORGERY-TOKEN&quot;: token
  11. },
  12. type: &#39;POST&#39;,
  13. url: `@Url.Action(&quot;GeneratePrintRecipeCards&quot;, &quot;MenuPrintout&quot;)?id=` + @Model.RecipeCardLabelId + `&amp;menuHeaderId=` + @Model.MenuHeaderId,
  14. success: function(response){
  15. console.log(response)
  16. const { errorMsg, progressValue } = response
  17. inProgressEle.hide();
  18. close.show();
  19. if (errorMsg) {
  20. toast(errorMsg, &quot;error&quot;)
  21. }
  22. else if (progressValue &gt; 0) {
  23. console.log(&quot;progress value:&quot; + progressValue);
  24. }
  25. else{
  26. expand.hide()
  27. collapse.hide()
  28. statusEle.text(&quot;Ready&quot;);
  29. completedEle.fadeIn()
  30. }
  31. }
  32. });
  33. }
  34. // get progress
  35. function getProgress() {
  36. setInterval(function(){
  37. $.ajax({
  38. url: &#39;@Url.Action(&quot;GeneratePrintRecipeCardsStatus&quot;, &quot;MenuPrintout&quot;)&#39;,
  39. type: &quot;GET&quot;,
  40. success: function (response) {
  41. console.log(response)
  42. $(&#39;#lblStatus&#39;).text(response)
  43. }
  44. })
  45. }, 5000)
  46. }
  47. &lt;/script&gt;
  48. // controller
  49. public class MenuPrintoutController : BaseController
  50. {
  51. private readonly IMenuLabelService _menuLabelService;
  52. private int _generateRecipeCardsStatus;
  53. private Progress&lt;int&gt; _progress;
  54. public MenuPrintoutController(IMenuLabelService menuLabelServicee)
  55. {
  56. _menuLabelService = menuLabelService;
  57. }
  58. // Is always zero
  59. public int GeneratePrintRecipeCardsStatus()
  60. {
  61. return _generateRecipeCardsStatus;
  62. }
  63. // Updates fine
  64. private void ReportProgress(int progress)
  65. {
  66. _generateRecipeCardsStatus = progress;
  67. }
  68. [HttpPost]
  69. [ValidateAntiForgeryToken]
  70. public async Task&lt;IActionResult&gt; GeneratePrintRecipeCards(int id, int menuHeaderId)
  71. {
  72. try
  73. {
  74. _progress = new Progress&lt;int&gt;(ReportProgress);
  75. var data = await _menuLabelService.DoAsync(int menuHeaderId, _progress);
  76. TempData.Put(&quot;PrintRecipeCards&quot;, data);
  77. return Json(new { Success = true });
  78. }
  79. catch (Exception exp)
  80. {
  81. return Json(new { ErrorMsg = exp.Message });
  82. }
  83. }
  84. }
  85. // service
  86. public interface IMenuLabelService
  87. {
  88. Task&lt;object&gt; DoAsync(int menuHeaderId, IProgress&lt;int&gt; progress);
  89. }
  90. public class MenuLabelService : IMenuLabelService
  91. {
  92. public async Task&lt;object&gt; DoAsync(int menuHeaderId, IProgress&lt;int&gt; progress)
  93. {
  94. var menuFoodItemsList = _context.FoodItemUnits
  95. .Where(x =&gt; x.MenuSectionFoodItemUnits.Any(y =&gt; y.Menusection.MenuheaderId == menuHeaderId))
  96. .Select(x =&gt; x.Fooditem)
  97. .ToList();
  98. var menuFoodItems = new List&lt;PrintLabel&gt;();
  99. var donePointer = 0;
  100. foreach (var menuFoodItem in menuFoodItemsList)
  101. {
  102. menuFoodItems.Add(menuFoodItem);
  103. // ...
  104. progress.Report((int)(++donePointer / (double)menuFoodItemsList.Count * 100));
  105. donePointer++;
  106. }
  107. return menuFoodItems;
  108. }
  109. }

答案1

得分: 1

每个请求都会创建一个新的控制器,因此有两个不同的_generateRecipeCardsStatus变量。

如果你只想支持单个服务器上的单个调用,可以将变量设为静态。

如果你想允许多次调用,那么你需要一种标识/查找机制。请注意,你还需要一种方法在状态过时(并且可能不再需要)时删除这些状态,因此这种查找不太像字典,而更像缓存。

如果你想将其部署到多个服务器上,那么你需要一个外部缓存,而不是将其保存在内存中。

英文:

A new controller is created for each request, so there are two different _generateRecipeCardsStatus variables.

If you only want to support a single call on a single server, you can just make the variable static.

If you want to allow multiple calls, then you'll need some kind of identifier/lookup mechanism. Note that you will also want a way to remove the statuses when they're too old (and presumably no longer needed), so this lookup is less of a dictionary and more of a cache.

If you want to deploy this to multiple servers, then you'll need an external cache rather than keeping it in memory.

huangapple
  • 本文由 发表于 2023年5月22日 17:18:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定