简体   繁体   English

使用ajax请求的结果作为变量

[英]Use the result of an ajax request as a variable

I would like to know how I can use the result of an ajax request as an "object". 我想知道如何将ajax请求的结果用作“对象”。 I'll try to explain. 我会试着解释一下。 I have an ajax request that get a number, every 2 seconds, to an xml file. 我有一个ajax请求,每2秒获取一个数字到xml文件。 Then I render it into my html. 然后我把它渲染成我的HTML。

Here is my js: 这是我的js:

   var url = window.location.pathname.split('/');
   var id = url[3];

setInterval(function() {
   $.ajax({
       type: "GET",
       url: "http://myxml",
       success: parseXml
   });
 }, 2000);

function parseXml(xml){
   $(xml).find("user").each(function() {

           if($(this).attr("id") === id ) {
               $(".DubScore").html($(this).attr("count"))
           }
       });
}

and my html: 和我的HTML:

 <div class="DubScore"> </div>

It works find, I have a count displayed to my page. 它找不到,我的页面显示了一个计数。

What I want to do, is to take this number and be able to do whatever I wan't with it in my html. 我想做的是取这个号码,并且能够在我的HTML中做任何我不想做的事情。 For example, name it "Score", and be able to do "Score" + 2 , and things like that. 例如,将其命名为“Score”,并且能够执行“Score”+ 2,以及类似的事情。

I hope my question is clear enough. 我希望我的问题很清楚。 Thank you for your help. 谢谢您的帮助。

You can parse the attribute value and store it in a global variable : 您可以解析属性值并将其存储在全局变量中:

var score;

function parseXml(xml){
   $(xml).find("user").each(function() {
           if($(this).attr("id") === id ) {
               score = parseInt($(this).attr("count"), 10);
           }
       });
}

Afterwards, you may do, for example, 之后,你可能会做,例如,

score += 2;
$(".DubScore").html(score);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM