简体   繁体   中英

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". I'll try to explain. I have an ajax request that get a number, every 2 seconds, to an xml file. Then I render it into my html.

Here is my 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:

 <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. For example, name it "Score", and be able to do "Score" + 2 , and things like that.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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