javascript,$ .ajax,变量名 [英] javascript, $.ajax, variable name

查看:130
本文介绍了javascript,$ .ajax,变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历数组并使用for循环分配变量。如下所示:

  function Person(姓名,状态){
this.name = name;
this.status = status;
}

var status = [];
var array = [bill,bob,carl,ton];
函数exAjax(function(){
for(var i = 0; i< array.length; i ++){
var name = array [i];
console。 log(name); =====>这给出正确的名称

$ .ajax({
url:xxxxxxx,
success:function(data){
if(data.stream === null){
var person = new Person(name,dead);
console.log(name); =====> return未定义,直到最后


status.push(人);
}
}

})
name = ;
}
})

我遇到的问题是该名称没有进入成功功能。我认为如果变量在当前范围内不存在,js会一直向上寻找变量吗?如果我尝试console.log名称,我的名称变量未定义!范围掌握我做错了什么?

解决方案

你可以使用 .queue() $。map()维护 name 的范围。此外,将 status 数组更改为具有属性 status 的对象,其中value是一个数组,以防止可能与<$ c冲突$ c> this.status of Person object。



注意,你也可以chain .promise(/ * queueName * /) .then()中执行任务时所有排队的函数在 queueName ,ieg,status已被调用, queueName .length 0



  function Person(name,status){this.name = name; this.status = status;} var blob = new Blob(['{stream:null}'],{type:application / json}); var url = URL.createObjectURL(blob); //更改` status`数组引用,例如,`arr`var arr = {status:[]}; var array = [bill,bob,carl,ton]; $(arr).queue( status,$ .map(array,function(curr){return function(next){var name = curr; // do asynchronous stuff $ .ajax({url:url,dataType:json})。then(function (data){if(data.stream == null){var person = new Person(name,dead); console.log(name,person); arr.status.push(person);}})。then (下一步)//在`status`queue}})中调用next函数。)dequeue(status)。promise(status)//当``status'`队列中的所有函数都完成时执行, //status`queue` .length`是`0`.then(function(){//`this`:`arr`作为jQuery对象//`this [0] .status`:包含对象的数组被推送到`arr.status` console.log(this [0] .status); // $(this).prop(status);});  

< pre cl ass =snippet-code-html lang-html prettyprint-override> < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery。 min.js>< / script>



jsfiddle < a href =https://jsfiddle.net/nnayjckc/2/ =nofollow> https://jsfiddle.net/nnayjckc/2/






您也可以使用 $。when() .apply() $。map(),返回相同的结果



  function Person(name,status){this.name = name; this.status = status;} var blob = new Blob(['{stream:null}'],{type:application / json}); var url = URL.createObjectURL(blob); //更改` status`数组引用,例如,`arr`var arr = {status:[]}; var array = [bill,bob,carl,ton]; $。when.apply($, $ .map(array,function(curr){var name = curr; return $ .ajax({url:url,dataType:json})。then(function(data){if(data.stream == null) {var person = new Person(name,dead); console.log(name,person); arr.status.push(person);}})}))。then(function(){console.log(arr) .status)});  

 < script src = https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"> < / script>  



jsfiddle https://jsfiddle.net/nnayjckc/3/


I'm trying to iterate over an array and assign a variable with a for loop. So something like this:

function Person(name, status){
  this.name = name;
  this.status = status;
}

var status = [];
var array = ["bill","bob","carl","ton"];
function exAjax(function(){
 for(var i = 0; i < array.length; i++){
   var name = array[i];
   console.log(name); =====> this gives the correct name

   $.ajax({
     url: xxxxxxx,
     success: function(data){
       if(data.stream === null){
         var person = new Person(name, "dead");
         console.log(name); =====> return undefined until the last
         person

         status.push(person);       
       }
     }

   })
   name = "";
 }
})

The problem I'm having is that name is not getting into the success function. I thought js keeps traveling upwards to look for the variable if it doesn't exist in it's current scope? I'm getting undefined for the name variable if I try to console.log name! Scope masters what am I doing wrong?

解决方案

You can use .queue(), $.map() to maintain scope of name. Also, change status array to an object having property status where value is an array to prevent possible conflict with this.status of Person object.

Note, you can also chain .promise(/* queueName */) to perform tasks at .then() when all queued functions in queueName, i.e.g., "status" have been called, queueName .length is 0.

function Person(name, status){
  this.name = name;
  this.status = status;
}

var blob = new Blob(['{"stream":null}'], {type:"application/json"});
var url = URL.createObjectURL(blob);
// change `status` array reference, e.g., to `arr`
var arr = {status:[]};
var array = ["bill","bob","carl","ton"];

$(arr).queue("status", $.map(array, function(curr) {
  return function(next) {
    var name = curr;
    // do asynchronous stuff
    $.ajax({url:url, dataType:"json"})
    .then(function(data) {
       if(data.stream == null){
         var person = new Person(name, "dead");
         console.log(name, person);
         arr.status.push(person);
       }
    })
    .then(next) // call next function in `"status"` queue
  }
}))
.dequeue("status")
.promise("status")
// do stuff when all functions in `"status"` queue have completed,
// `"status"` queue `.length` is `0`
.then(function() {
   // `this` : `arr` as jQuery object
   // `this[0].status`: array containing objects pushed to `arr.status`
   console.log(this[0].status); // $(this).prop("status");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

jsfiddle https://jsfiddle.net/nnayjckc/2/


You can alternatively use $.when(), .apply(), $.map(), to return same result

function Person(name, status) {
  this.name = name;
  this.status = status;
}

var blob = new Blob(['{"stream":null}'], {
  type: "application/json"
});
var url = URL.createObjectURL(blob);
// change `status` array reference, e.g., to `arr`
var arr = {
  status: []
};
var array = ["bill", "bob", "carl", "ton"];

$.when.apply($, $.map(array, function(curr) {
  var name = curr;
  return $.ajax({
      url: url,
      dataType: "json"
    })
    .then(function(data) {
      if (data.stream == null) {
        var person = new Person(name, "dead");
        console.log(name, person);
        arr.status.push(person);
      }
    })
}))
.then(function() {
  console.log(arr.status)
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">  
</script>

jsfiddle https://jsfiddle.net/nnayjckc/3/

这篇关于javascript,$ .ajax,变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆