在ajax代码之外访问ajax响应数据

时间:2019-11-11 02:56:10

标签: javascript jquery ajax

我正在尝试在ajax代码之外访问j_data。我在该线程How do I return the response from an asynchronous call?中找到了关于如何使用承诺,延迟对象或回调进行详细响应的详细信息,但我仍然不确定如何将所写内容应用于我的情况。例如,回调代码涉及处理函数中的数据并将处理后的数据交还给ajax所在的函数。下面的代码用于在按下搜索按钮时发生的ajax调用。然后,它将使用该数据显示在图像滑块中。我所希望的是能够在我的Ajax代码之外使用j_data,以便可以在for循环中使用j_data.url之类的东西。谢谢你的帮助。

$(function() {

  $('#search').click(function first(j_data) {
    var nameVal = $('#shouhinName').val();
    var makerVal = $('#makerName').val();
    var categoryVal = $('#selectText').val();
    var sliderVal = $('#hideme').val();

    $.ajax({
      type: "POST",
      url: "shelf/test",
      data: {


        shouhinName: nameVal,
        makerName: makerVal,
        selectText: categoryVal,
        best: sliderVal

      },
      success: function hi(j_data) {

        alert(j_data.url);

        console.log(j_data);
        $('.search-items').children().remove();

        let index = 0;
        const display = "table"; 
        const x = 0;
        const y = 0;
        var hdnName = document.getElementById("sendServ");
        hdnName.value = '';
        document.body.style.display = display;
        var selectedItem = document.getElementById("selectedItem");





        for (i = 0; i < 200; i++) {

          $('.search-items').slick('slickRemove', 0);

        canvasArr = [];
        for (const image of j_data.url) {

          // console.log();
          //each image will correspond to a canvas element
          const canvas = document.createElement("canvas");
          canvas.setAttribute("name", "canvas");
          const ctx = canvas.getContext("2d");


          //each canvas element will has is own properties (in this case all the same)
          canvas.id = "optiona" + [index];

          var canId = canvas.id;
          var tooltip = j_data.tooltip;

          canvas.setAttribute('width', '75px');
          canvas.setAttribute('padding-top', '56.25%');
          canvas.setAttribute('object-fit', 'contain');
          canvas.setAttribute('data-html', 'true');

          canvas.className = 'searching';


          var div = document.createElement("div");
          div.setAttribute('data-html', 'true');
          div.id = j_data.itemid[index]; //image.slice(26, 34);
          var content = document.createTextNode(index + 1);



          drawImages(canvas, 7);

          canvas.addEventListener("click", optionClicke, false);

          var text = j_data.tooltip[index];

          div.title = text;
          document.getElementById('search-slider').appendChild(div);
          document.getElementById(div.id).appendChild(canvas);
          document.getElementById(div.id).appendChild(content);



          document.getElementById(div.id).addEventListener('contextmenu', (ev) => {
            ev.preventDefault();

            if (image !== '/check/assets/img/noimage.png') {
              window.open(`/check/assets/img/${image} `, 'mywindow', "width=500,height=500");
            } else {}

          }, false);

          console.log(image);
          index++;

        }


        function drawImages(canvas, f) {

          const ctx = canvas.getContext("2d");
          const background = new Image();
          const ctr = selectedItem.getContext("2d");

          index = canvas.id.replace(/\D/g, "");

          if (f == 7) {


            if (j_data.url[index] !== '/check/assets/img/noimage.png') {
              background.src = "/check/assets/img/" + j_data.url[index];
            } else {
              background.src = '/check/assets/img/noimage.png'
            }

            background.onload = function() {

              ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

            };
          }




          if (f == 1) {
            background.src = "/check/assets/img/" + images.url[index];

            background.onload = function() {
              ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

            };

          }



          /////

          if (f == 2) {
            background.src = "/check/assets/img/shelf/photo/" + topData.rightFace[index - images.url.length - 1];

            background.onload = function() {
              ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

            };

          }


          ////

          if (f == 3) {
            background.src = "/check/assets/img/shelf/photo/" + topData.rightTag[index];

            background.onload = function() {
              ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
            };

          }

          ////

          if (f == 4) {
            if (topData.leftTag[index - images.url.length - topData.rightFace.length - 1] !== "error.jpg") {
              background.src = "/check/assets/img/shelf/photo/" + topData.leftFace[index - images.url.length - topData.rightFace.length - 1];
            } else {
              background.src = "/check/assets/img/" + topData.leftFace[index - images.url.length - topData.rightFace.length - 1];
            }
            //   console.log( topData.leftTag[index - leftLoop]);
            background.onload = function() {
              ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
            };

          }
          ////

          if (f == 5) {
            if (topData.leftFace[index] !== "error.jpg") {
              background.src = "/check/assets/img/shelf/photo/" + topData.leftTag[index];


            } else {
              background.src = "/check/assets/img/" + topData.leftTag[index];
            }

            // console.log(background.src);
            background.onload = function() {
              ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

            };

          }
          if (f == 6) {
            background.src = "/check/assets/img/" + topData.zenkai;
            console.log(background.src);
            // console.log(background.src);
            background.onload = function() {
              ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
            }
          }

        }

        function drawX(canvas, item) {
          const ctx = canvas.getContext("2d");


          ctx.beginPath();
          ctx.arc(40, 75, 25, 0, 2 * Math.PI, false);
          ctx.lineWidth = 5;
          ctx.strokeStyle = "#FF0000";
          ctx.closePath();
          ctx.stroke();
          //     console.log(item);
          hdnName.value = item;

        }



        function clear(canvas) {
          //   console.log("E: clearing canvas " + canvas.id);

          canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);


          drawImages(selectedItem);

          if (canvas.className == 'suitei') {
            f = 1;
            drawImages(canvas, f);
          }
          if (canvas.className == 'righty') {
            f = 2;
            drawImages(canvas, f);
          }
          if (canvas.className == 'rTag') {
            f = 3;
            drawImages(canvas, f);
          }
          if (canvas.className == 'lefty') {
            f = 4;
            drawImages(canvas, f);
          }
          if (canvas.className == 'lTag') {
            f = 5;
            drawImages(canvas, f);
          }
          if (canvas.className == 'zenkai') {
            f = 6;
            drawImages(canvas, f);
          }
          if (canvas.className == 'searching') {
            f = 7;
            drawImages(canvas, f);
          }


        }

        function optionClicke(e) {
          log = true;
          const canvas = document.getElementsByTagName("canvas");
          const selectedItem = document.getElementById("selectedItem");

          var hdnName = document.getElementById("sendServ");
          let index = 0;


          for (const option of canvas) {
            console.log(canvas.length);
            if (log)
              //  console.log("I: User clicked at option " + e.target.id + ":" + option.id);
              log = false;
            if (e.target.id === option.id) {
              // console.log("R: Drawing request at canvas " + option.id);
              // console.log(j_data.itemid[index]);
              const item = j_data.itemid[option.id.split('optiona', -1)[1]];
              console.log('draw' + item);
              //    console.log(index);
              // option = canvasArr[index];
              drawX(option, item);

            } else {
              //   console.log("R: Clearing request at canvas " + option.id);
              clear(option);
              //console.log('clear'+item);
            }
            index++;
          }

        }

        $('.search-items').slick('unslick').slick('reinit');
        $(document).ready(function() {
          $('.search-items').not('.slick-initialized').slick({
            infinite: false, //true
            slidesToShow: 8,
            slidesToScroll: 8,
            arrows: true,
            centerMode: false,
            width: 200,
            prevArrow: $('.prev'),
            nextArrow: $('.next')
          });
        });

      },
      error: function(xhr, status, error) {
        console.log("post error");
        console.log(error);
        alert(error);
      },
      complete: function(xhr, status) {
        console.log("fin");
      },
    });
  });
});

编辑:

我试图使我的ajax变得更简单,只是为了接收我的数据。我尝试过在这里使用回叫,但是在我的函数之外使用j_data并没有运气。

$('#search').click(function ajaxCall(j_data) {
                  var nameVal = $('#shouhinName').val();
                  var makerVal = $('#makerName').val();
                  var categoryVal = $('#selectText').val();
                  var sliderVal = $('#hideme').val();

                  $.ajax({
                        type: "POST",
                        url: "shelf/test",
                        data: {


                              shouhinName: nameVal,
                              makerName: makerVal,
                              selectText: categoryVal,
                              best: sliderVal

                        },
                        success: j_data

                  });
            });

0 个答案:

没有答案