AJAX POST中的随机数组值

时间:2019-02-22 18:03:51

标签: javascript ajax

开始钻研墙壁以找出如何通过以下代码获得一致的结果...我基本上想运行2个相同大小的数组,以便在整个站点范围内查找并通过API进行替换,但是代码似乎可以遍历数组的随机值-有时它将运行第一个值两次或遍历所有4个值以进行搜索和替换-从来都不一样...任何人都知道如何修复此代码或有没有更好的方法来编写此代码?抱歉,如果我不清楚...

var searchid;
var origArray;
var suggArray;
var orig = new Array();
var sugg = new Array();
var params;

orig = ["originalVal1", "originalVal2", "originalVal3", "originalVal4", "originalVal5", "originalVal6"];

sugg = ["replaceVal1", "replaceVal2", "replaceVal3", "replaceVal4", "replaceVal5", "replaceVal6"];

var counter = 0;

function getData() {

  if (counter === orig.length) {
    counter = 0;
  }

  gadget.ready().then(gadget.fetch).then(function() {

    params = {
      authorization_token: gadget.token,
      replace: true,
      path: "/mypath/aboutus/timelineGallery.pcf",
      site: "www",
      srchstr: orig[counter],
      rplcstr: sugg[counter]
    };

    $.ajax({
      async: true,
      type: "POST",
      url: "http://myapi/sites/findreplace",
      data: params,

      success: function(data) {

        searchid = data.id;

        $('p').append(searchid).append('<br />');

        counter++;
        if (counter < orig.length) getData();
      }
    });

  });
}

1 个答案:

答案 0 :(得分:0)

在设置async:true时,ajax调用将异步运行,因此下一次调用中可能不会更新var counter的值。您可以设置async:false或获取ajax成功计数器,如下所示,

counter = function () {
    var tmp = null;
    $.ajax({
        async: true,
        type: "POST",
        url: "http://myapi/sites/findreplace",
        data: params,
        'success': function (data) {
         searchid = data.id;

         $('p').append(searchid).append('<br />');

         tmp=counter++;
        }
    });
    return tmp;
}();
if (counter < orig.length) getData();

注释()在倒数第二行。