首页 > 解决方案 > 如何在ajax响应javascript jquery中重新分配变量值

问题描述

我已经花时间知道为什么当我的 ajax 响应成功时无法重新分配我的变量,但结果仍然没有让我的变量值发生任何事情,我已经做了一些技巧来重新分配我的变量值但结果仍然相同没有任何改变,这里是我的代码:

setTimeout(() => {
   let scrollHeight = 1500;
   $(".my-class-content-scroll").animate({scrollTop: scrollHeight}, 5000);

   $(".my-class-content-scroll").on('scroll', function () {
       let newScrollHeight = 0 ;

       if (scrollHeight >= 1500) {
          $.ajax({
            url: `/my-url`,
            method: "GET",
            dataType: "JSON",
            success: function (success) {
               /* my process when response is success */
               /* start reassign the value */
               const newValue = $(".my-class-content-scroll").prop("scrollHeight");
               newScrollHeight = newValue
            }
          });
       }
       console.log(newScrollHeight) /* <= the result is giving 0 value */
   })
}, 1000)

对于另一个技巧,我尝试使用函数重新分配变量值,如下所示:

setTimeout(() => {
   let scrollHeight = 1500;
   $(".my-class-content-scroll").animate({scrollTop: scrollHeight}, 5000);

   $(".my-class-content-scroll").on('scroll', function () {
       let newScrollHeight = 0 ;
       
       function setScrollHeight (height) {
           newScrollHeight = height
       }

       if (scrollHeight >= 1500) {
          $.ajax({
            url: `/my-url`,
            method: "GET",
            dataType: "JSON",
            success: function (success) {
               /* my process when response is success */
               /* start reassign the value */
               const newValue = $(".my-class-content-scroll").prop("scrollHeight");
               setScrollHeight(newValue)
            }
          });
       }
       console.log(newScrollHeight) /* <= the result is still same than before and giving 0 value */
   })
}, 1000)

如果有人找到有关我的问题的答案,我希望任何人都可以向我解释为什么我的方法不起作用,谢谢各位好人

标签: javascriptjquery

解决方案


推荐阅读