错误数组Ajax承诺使用“when”

时间:2017-02-08 19:43:12

标签: javascript jquery ajax

我在使用多个ajax调用时遇到错误,我把它放在一个数组中,完成所有操作后我需要捕获。 我的代码是这样的:

var userId=[1,2,3];
var ajaxR = [];
for (var us in userId) {
    var usId = userId[us];
    ajaxR.push($.ajax({
        type: "GET",
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "myurl",
        data: { id: usId }   
    }));
}
$.when.apply($, ajaxR).always(function (e) {
    //Here I have the error but arguments it's ok
    var objects = arguments;      
});

当我对此代码进行debbug时,我在$ .when函数中出错:

Uncaught TypeError: Cannot read property '0' of undefined

更新

我的完整功能是:

 function UserFromWS(userId) {
        var users = [];
        var ajaxR = [];
        for (var us in userId) {
            var usId = userId[us];
            ajaxR.push($.ajax({
                type: "GET",
                async: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url:  "url",
                data: { id: usId }   
            }));
        }
        $.when.apply($, ajaxR).always(function (e) {
            var obj = arguments;
            return obj;
        }); 
        // return users;
    }

如果我将return users;放在函数末尾,则错误消失。但它返回用户数组为空,返回obj之前。我需要以这种方式调用函数:

var allUsers = UserFromWS ([1,2,3]);

该函数应在obj promise中返回$.when

2 个答案:

答案 0 :(得分:0)

要检查的第一点是" userId"正在作为数组传递。然后需要修改for循环以正确循环数组(Why is using "for...in" with array iteration a bad idea?)。

此功能还需要返回一个承诺:

 function UserFromWS(userId) {
        var users = [];
        var ajaxR = [];
        for (var i = 0; i< userId.length; i++) {
            var usId = userId[i];
            ajaxR.push($.ajax({
                type: "GET",
                async: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                url:  "url",
                data: { id: usId }   
            }));
        }
        return $.when.apply($, ajaxR).done(function (e) {
            var obj = arguments;
            return obj;
        }); 
        // return users;
    }

此外,您还需要等待此功能的结果:

var users = [10];

UserFromWS(users).then(function(result) { /* do stuff now */ });

答案 1 :(得分:-1)

为什么要将ajax调用保存到数组中,JQuery可以自己识别请求,并且可以多次调用相同的$ .ajax()而不会出错。

示例:

package com.example.moultitouch;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity 
{ 
    TextView[] textView = new TextView[6]; // 0:common metrics 1-5:finger details   
    int pointersCount = -1;
    int action = 0;
    int actionMasked = 0;
    String actionString = "NOT INIT";
    Display display;
    int iViewWidth = 0;

    int motionsCounter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_motion_event);
        display = getWindowManager().getDefaultDisplay();
        iViewWidth  = display.getWidth();
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);       

        for ( int i = 0; i < 6; i++ )
        {
            textView[i] = new TextView(this);
            textView[i].setWidth(iViewWidth);
            textView[i].setTextSize(16);
            textView[i].setTextColor(Color.WHITE);
            textView[i].setBackgroundColor(Color.BLACK);
            layout.addView(textView[i]);
        }
        textView[0].setText("Touch the screen to start");
        setContentView(layout);
    }

@Override 
public boolean onTouchEvent(MotionEvent event)  
{
    int i = 0;
    pointersCount = event.getPointerCount();
    action = event.getAction() & MotionEvent.ACTION_MASK;
    motionsCounter++;
    actionMasked = event.getActionMasked();
    if (action == MotionEvent.ACTION_DOWN ) 
        actionString = "DOWN";
    else if (action == MotionEvent.ACTION_POINTER_DOWN ) 
        actionString = "POINTER DOWN";
    else if (action == MotionEvent.ACTION_POINTER_UP ) 
        actionString = "POINTER UP";
    else if (action == MotionEvent.ACTION_MOVE )
        actionString = "MOVE";
    else if (action == MotionEvent.ACTION_UP )
    {
        actionString = "ALL UP";
        pointersCount = 0;
    }
    else
        actionString = "UNKNOWN(" + action + ")";

    textView[0].setText (pointersCount + " POINTERS. ACTION:[" + action +"] " + actionString + ". (MASKED:" + actionMasked +"). " + motionsCounter + " MOTIONS");

    for (i = 0; i < pointersCount; i++)
    {
        int x = (int) event.getX(i);
        int y = (int) event.getY(i);            
        int id = event.getPointerId(i);
        textView[i+1].setText("idx: " + i + " id: " + id + ". (" + x + "," + y +")");
    }
    for ( i = pointersCount; i < 5; i++ )
        textView[i+1].setText("- - - - - ");
    return true;
}
}

或者如果您想继续使用您的系统,请在使用承诺时知道      见https://api.jquery.com/jquery.when/