【问题标题】:How to store value in variable with .load();如何使用 .load() 将值存储在变量中;
【发布时间】:2025-12-27 02:30:12
【问题描述】:

我想比较两个变量,oldRefreshnewRefresholdRefresh 在输入中的值很容易通过键入 var oldRefresh= $('#oldrefresh').val(); 将其存储在 oldRefresh

但是newRefresh,很难得到它,我需要用.load();从另一个文件中得到它

这是代码:

var oldRefresh= $('#oldrefresh').val();

setInterval(function ()
{
    $('#noti_number').load('include/js_notification_count.php?n=".$_SESSION['username']."');
    });
}, 5000); 

我试过这个:

var newRefresh = setInterval(function ()
{
    $('#noti_number').load('include/js_notification_count.php?n=".$_SESSION['username']."');
    });
}, 5000); 
alert(newRefresh);

这个结果是2,加载的结果应该是0

所以我尝试了这个

setInterval(function ()
{
    var newRefresh = $('#noti_number').load('include/js_notification_count.php?n=".$_SESSION['username']."');
    });
    alert(newRefresh);
}, 5000); 

结果是[object Object]。我不明白。如何将load 值放入变量中?

【问题讨论】:

  • 不要使用.load()。它用于用 Ajax 加载的文件替换 DOM 元素的内容。请改用.ajax()
  • 另外 load() 返回一个 jQuery 对象,不是我认为你想要的。
  • 只是一条评论,与您发布的问题有些无关:您可能想重新考虑将n=".$_SESSION['username']." 传递回您的js_notification_count.php 脚本,而只需在PHP 端访问您的$_SESSION['username]。这可以使您的客户端和服务器端逻辑更清晰。

标签: javascript jquery function variables load


【解决方案1】:

jQuery 加载正在用 js_notification_count.php 文件返回的信息替换对象。您可以添加 .text() 或更改加载功能,例如:

setInterval(function () {
   $('#noti_number').load('include/js_notification_count.php?n=<?=$_SESSION['username']?>', function(response, status, xhr) {
         newRefresh = response;
         alert(newRefresh);
      }
   });
}, 5000);

不过,我会使用 ajax(如果您不需要 noti_number 来获得返回的响应),例如:

setInterval(function () {
   $.ajax({
      type: "GET", //Change to whatever method type you are using on your page
      url: "include/js_notification_count.php",
      data: { n: "<?=$_SESSION['username']?>" }
   }).done(function(result) {
      newRefresh = result;
      alert(newRefresh);
   });
}, 5000); 

【讨论】:

  • 给我一个关于 .text() 的例子。
  • 尝试使用此处的其他 2 个示例之一。 .text() 将在 .load(url).text() 之后,但不确定是否可靠。调用完成后调用其他函数。
  • n 请求无效,在 ajax 中,我用我的名字 n: 'AbdullahSalma' 更改会话,所以结果应该是 60。在include/js_notification_count.php 我输入if(empty($_G['n'])){echo "empty";}else{..} 警报显示我empty
【解决方案2】:

如果你这样做,你应该能够比较这些值:

$('#noti_number').load(
   'include/js_notification_count.php?n=".$_SESSION['username']."',
   function(aData) {
      //Do your comparison here.
   }
)

传回的数据应该是服务器的响应。

【讨论】:

  • 我将oldRefresh 与什么进行比较?数据?
  • 是的,没错。 aData 是服务器作为文本字符串的确切响应