JQuery Ajax:动态div元素的随机顺序

时间:2017-08-08 16:06:55

标签: javascript jquery ajax

我有一个我需要在页面上呈现的图像列表。该图片来自第三方API。我得到列表并使用for循环我显示图像。

var count = imageIds.length;
for (var i = 0; i < count; i++) {
GetImage(imageIds[i]);
}

function GetImage(imageId){
//Ajax request here. Returns string "data" for image.
//Once the request finishes, I update the div's content like:
_targetDiv.append('<img class="thumb" src="data:image/jpeg;base64,' + data + '"/>';
}

问题是图像没有按顺序渲染。以上代码基于完成的请求以任何顺序排列图像。我需要渲染图像1,然后是图像2,然后是图像3,依此类推......

解决方法是什么?

2 个答案:

答案 0 :(得分:1)

创建一个请求承诺数组,并使用$.when()以与原始数据相同的顺序处理响应数据

&#13;
&#13;
package com.example.rushikesh.assignment3;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

TextView textView;
EditText edt;
Button btnAdd, btnRemove,btnSet;
LinearLayout linearLayout;
EditText editText;
int count = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

    textView = new TextView(this);
    textView.setLayoutParams(layoutParams);

    edt = new EditText(this);
    edt.setLayoutParams(layoutParams);


    btnAdd = new Button(this);
    btnAdd.setLayoutParams(layoutParams);
    btnAdd.setText("+");


    btnRemove = new Button(this);
    btnRemove.setLayoutParams(layoutParams);
    btnRemove.setText("-");

    btnSet = new Button(this);
    btnSet.setLayoutParams(layoutParams);
    btnSet.setText("SET");

    linearLayout = new LinearLayout(this);
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setLayoutParams(layoutParams);
    linearLayout.addView(textView);
    linearLayout.addView(edt);
    linearLayout.addView(btnAdd);
    linearLayout.addView(btnRemove);
    linearLayout.addView(btnSet);

    setContentView(linearLayout);

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            editText = new EditText(MainActivity.this);
            editText.setLayoutParams(layoutParams);
            linearLayout.addView(editText);
            count++;
        }
    });

    btnRemove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(count > 0)
            {
                linearLayout.removeViewAt(5);
                count--;

            }else
            {
                Toast.makeText(MainActivity.this, "No edit text found", Toast.LENGTH_SHORT).show();
            }
        }
    });

    btnSet.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

   }
}
&#13;
var imageIds = [1,2,3,4,5];

var promiseArray = imageIds.map(getImage);

$.when.apply(null, promiseArray).then(function(){
   // array of data received for each request, in same order as original data array
   var array = [].slice.call(arguments);

   array.forEach(function(item){
      $('body').append('<p> Item #' + item.id +'</p>')
   })
}).fail(function(){
   // one or more of the requests failed...handle error 
});

function getImage(imageId){ 
   var url ='https://simple-express-cors-endpoint-be970g7kgnc3.runkit.sh';
   // return the request promise
   return $.post(url, {id: imageId}).then(function(data){
       console.log('Request for #'+imageId+' completed');
       // resolve with response data
       return data;
   });
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

有两个选项可以保留请求和响应的顺序。

  1. 在加载所有图像后最终渲染所有图像

    var count = imageIds.length;
    var responses = [];
    var completedCount = 0;
    
    for (var i = 0; i < count; i++) {
        GetImage(imageIds[i], i);
    }
    
    function GetImage(imageId, requestIndex){
        // Ajax query goes here
        // Push the response and the requestIndex into our responses Array
        responses.push({ index: requestIndex, data: data });
        completedCount = completedCount + 1;
        // Render the images only after all responses have been obtained
        if(completedCount === count) {
            renderAllImages();
        }
    }
    
    function renderAllImages() {
        // Sort responses based on the request Index so that we preserve ordering
        responses.sort(function(a, b) {
            var keyA = a.requestIndex,
            var keyB = b.requestIndex;
            // Compare the 2 dates
            if(keyA < keyB) return -1;
            if(keyA > keyB) return 1;
            return 0;
        });
    
        // Render all images finally after sorted
        for(var i=0; i<responses.length; i++) {
            _targetDiv.append('<img class="thumb" src="data:image/jpeg;base64,' + responses[i].data + '"/>';
    
        }
    }
    
  2. 在加载图像时渲染图像,保留发送请求的顺序

    var count = imageIds.length;
    var responses = [];
    var completedCount = 0;
    
    for (var i = 0; i < count; i++) {
        GetImage(imageIds[i], i);
    }
    
    function GetImage(imageId, requestIndex){
        // Ajax query goes here
        // Push the response and the requestIndex into our responses Array
        responses.push({ index: requestIndex, data: data });
        completedCount = completedCount + 1;
        // Render all the images we have loaded so far after each response
        renderAllImages();
    }
    
    function renderAllImages() {
        // Sort responses based on the request Index so that we preserve ordering
        responses.sort(function(a, b) {
            var keyA = a.requestIndex,
            var keyB = b.requestIndex;
            // Compare the 2 dates
            if(keyA < keyB) return -1;
            if(keyA > keyB) return 1;
            return 0;
        });
    
        // Render all images finally after sorted
        for(var i=0; i<responses.length; i++) {
            _targetDiv.append('<img class="thumb" src="data:image/jpeg;base64,' + responses[i].data + '"/>';
    
        }
    }