简体   繁体   English

如何通过ajax发送以下数组中的每个元素?

[英]How do I send through ajax each element from the following array?

Send through ajax each element from the following array. 通过ajax发送以下数组中的每个元素。 Note: Each request must be made once the previous has finished. 注意:每个请求都必须在前一个请求完成后进行。 ['This', 'is', 'a', 'fake, 'array'] ['This','is','a','fake,'array']

I am a little confused by this question because I thought Ajax is asynchronous, meaning the script keeps sending requests to the server without waiting for the reply. 这个问题让我有些困惑,因为我认为Ajax是异步的,这意味着脚本会一直向服务器发送请求,而无需等待答复。

***Was downvoted so going to clarify something: It specifically states in the problem statement that the REQUEST must be made synchronously. ***被否决了,所以要澄清一下:它在问题说明中特别指出必须同步进行REQUEST。 I do realize that there are better ways of doing this via def/promises asynchronously so order remains for the result but that isn't the request. 我确实意识到,有更好的方法可以通过def / promises异步执行此操作,因此结果的顺序保持不变,但这不是请求。

Ajax has a async parameter you can set to false which will block until call completion. Ajax有一个异步参数,您可以将其设置为false,它将阻塞直到调用完成。

Per documentation: 每个文档:

async (default: true) Type: Boolean By default, all requests are sent asynchronously (ie this is set to true by default). async(默认:true)类型:Boolean默认情况下,所有请求都是异步发送的(即默认情况下设置为true)。 If you need synchronous requests, set this option to false. 如果需要同步请求,请将此选项设置为false。 Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. 跨域请求和dataType:“ jsonp”请求不支持同步操作。 Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. 请注意,同步请求可能会暂时锁定浏览器,从而在请求处于活动状态时禁用任何操作。 As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; 从jQuery 1.8开始,不建议使用async:false和jqXHR($ .Deferred); you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done(). 您必须使用成功/错误/完成回调选项,而不要使用jqXHR对象的相应方法,例如jqXHR.done()。

http://api.jquery.com/jquery.ajax/ http://api.jquery.com/jquery.ajax/

Example: 例:

$.each(["This", "is", "a", "fake", "array"], function( index, value ) {
 $.ajax({
  type: 'POST',
  dataType: 'json',
  url: '/echo/json/',
  data : { json: JSON.stringify( value ) },
  async: false,
  success: function(data) { alert(data);}  
 }); 
});

Working fiddler example: https://jsfiddle.net/zm9bb4xk/ 工作提琴手示例: https : //jsfiddle.net/zm9bb4xk/

I was talking about JQuery Ajax . 我在谈论JQuery Ajax

So, first, based on documentation, Ajax has many events that run at certain times, for example: 因此,首先,基于文档,Ajax具有许多在特定时间运行的事件,例如:

beforeSend (Local Event) beforeSend(本地事件)

This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.) 此事件在启动Ajax请求之前触发,允许您修改XMLHttpRequest对象(如果需要,可以设置其他头)。

error (Local Event) 错误(本地事件)

This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request). 仅在请求发生错误时才调用此事件(对于请求,您永远不能同时发生错误和成功回调)。

complete (Local Event) 完成(本地活动)

This event is called regardless of if the request was successful, or not. 无论请求是否成功,都将调用此事件。 You will always receive a complete callback, even for synchronous requests. 即使对于同步请求,您将始终收到完整的回调。

success (Local Event) 成功(本地活动)

This event is only called if the request was successful (no errors from the server, no errors with the data). 仅当请求成功时才调用此事件(服务器无错误,数据无错误)。

More in documentation. 更多文档。

Second, following your example (you have to complete this with your own data and this code is not tested, maybe it has some small sintax errors), an approximation is: 其次,按照您的示例 (您必须使用自己的数据来完成此操作,并且此代码未经测试,可能有一些小的sintax错误), 其近似值为:

//  Variables
var myArray = ["This", "is", "a", "fake", "array"];
var globalIndex = 0;


//  Function for Ajax Calls
function myFunction(){
    $.ajax({
        url: 'myURL',                       //  Your own controller/url

        type: "GET",                        //  Or POST

        dataType: "json",                   //  Or other datatype

        data: {
            arrayContent: myArray[globalIndex]  //  arrayContent = your controller param name   
        },      

        /**
         * A function to be called if the request succeeds.
         */
        success: function(data) {       

            alert('Load was performed. Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information! '); 
            alert(data);                //  Do what you want with your data, this is an example 

            globalIndex = globalIndex +1;           
            //  Recursive/next call if current call is finished OK and there are elements
            if(globalIndex < myArray.length){
                myFunction();
            }
        },

        /**
         * A function to be called if the request fails. 
         */
        error: function(jqXHR, textStatus, errorThrown) {

            alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');

            alert('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
            console.log('jqXHR:');
            console.log(jqXHR);
            console.log('textStatus:');
            console.log(textStatus);
            console.log('errorThrown:');
            console.log(errorThrown);

            //  We don't do a recursive/next call because current call has failed
        },
    });
}

//  First call to myFunction

myFunction();

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

相关问题 在 Javascript 中,循环对象数组时,如何将每个元素的名称发送到控制台? - In Javascript, when looping through an array of objects, how do I send each element's name to the console? 在以下情况下如何从每个数组元素中删除\\&#39;? - How to remove \' from each array element in following scenario? 如何使数组中的每个元素成为另一个数组? - How do I make each each element in array another array? 我有一个贯穿数组的 API,我想在每个数组元素上向客户端发送数据 - I have an API that runs through an array and I want to send data to the client on each array element 如何通过Ajax从Javascript向Java Servlet发送字节数组 - How to send byte array from javascript to java servlet through ajax 如何通过 ajax 从表单发送 POST 数据数组? - How to send array of POST data from form through ajax? 如何检索通过ajax从控制器发送到视图的数组? - how to retrieve the array which is send from controller to the view through ajax? 如何从 javascript 到 ajax 发送和检索数组 - How to send and retrieve an array from javascript through ajax 如何通过javaScript和Ajax发送“放置”请求? - how do I send 'put' request through javaScript & Ajax? 如何通过ajax将表单发送到我的php页面 - How do I send a form through ajax to my php page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM