读取当前文本输入值后调用Ajax

时间:2017-08-03 13:26:40

标签: javascript jquery ajax

我正在按照这个答案https://stackoverflow.com/a/20698523/1695685来阅读手持式条形码扫描仪的价值。代码工作正常,如答案中所述(小提琴附在上面的链接中)

但是,我想要做的是在读取条形码后根据文本输入的当前值进行一些ajax调用。

我面临的问题是,如果我多次扫描条形码,按下按钮后会触发ajax调用相同的次数(触发ajax调用)。对于例如如果我读了4个条形码,我将进行4次相同的ajax调用(在我的情况下为http://localhost:51990/Home/DecodeScanner)。我所追求的是在按下按钮后只拨打一个电话,但只读取文本输入框中的最新值。

每次我可以扫描条形码时,文本输入框都会显示新值(之前的值被覆盖)。但是,按下#scanner-verify-button按钮时,ajax调用也会触发所有先前的扫描。

这是我修改后的Fiddle我的自定义ajax调用

/*
    This code will determine when a code has been either entered manually or
    entered using a scanner.
    It assumes that a code has finished being entered when one of the following
    events occurs:
        • The enter key (keycode 13) is input
        • The input has a minumum length of text and loses focus
        • Input stops after being entered very fast (assumed to be a scanner)
*/

var inputStart, inputStop, firstKey, lastKey, timing, userFinishedEntering;
var minChars = 3;

// handle a key value being entered by either keyboard or scanner
$("#scanInput").keypress(function(e) {
  // restart the timer
  if (timing) {
    clearTimeout(timing);
  }

  // handle the key event
  if (e.which == 13) {
    // Enter key was entered

    // don't submit the form
    e.preventDefault();

    // has the user finished entering manually?
    if ($("#scanInput").val().length >= minChars) {
      userFinishedEntering = true; // incase the user pressed the enter key
      inputComplete();
    }
  } else {
    // some other key value was entered

    // could be the last character
    inputStop = performance.now();
    lastKey = e.which;

    // don't assume it's finished just yet
    userFinishedEntering = false;

    // is this the first character?
    if (!inputStart) {
      firstKey = e.which;
      inputStart = inputStop;

      // watch for a loss of focus
      $("body").on("blur", "#scanInput", inputBlur);
    }

    // start the timer again
    timing = setTimeout(inputTimeoutHandler, 500);
  }
});

// Assume that a loss of focus means the value has finished being entered
function inputBlur() {
  clearTimeout(timing);
  if ($("#scanInput").val().length >= minChars) {
    userFinishedEntering = true;
    inputComplete();
  }
};


// reset the page
$("#reset").click(function(e) {
  e.preventDefault();
  resetValues();
});

function resetValues() {
  // clear the variables
  inputStart = null;
  inputStop = null;
  firstKey = null;
  lastKey = null;
  // clear the results
  inputComplete();
}

// Assume that it is from the scanner if it was entered really fast
function isScannerInput() {
  return (((inputStop - inputStart) / $("#scanInput").val().length) < 15);
}

// Determine if the user is just typing slowly
function isUserFinishedEntering() {
  return !isScannerInput() && userFinishedEntering;
}

function inputTimeoutHandler() {
  // stop listening for a timer event
  clearTimeout(timing);
  // if the value is being entered manually and hasn't finished being entered
  if (!isUserFinishedEntering() || $("#scanInput").val().length < 3) {
    // keep waiting for input
    return;
  } else {
    reportValues();
  }
}

// here we decide what to do now that we know a value has been completely entered
function inputComplete() {
  // stop listening for the input to lose focus
  $("body").off("blur", "#scanInput", inputBlur);
  // report the results
  reportValues();
}

function reportValues() {
  // update the metrics
  $("#startTime").text(inputStart == null ? "" : inputStart);
  $("#firstKey").text(firstKey == null ? "" : firstKey);
  $("#endTime").text(inputStop == null ? "" : inputStop);
  $("#lastKey").text(lastKey == null ? "" : lastKey);
  $("#totalTime").text(inputStart == null ? "" : (inputStop - inputStart) + " milliseconds");
  if (!inputStart) {
    // clear the results
    $("#resultsList").html("");
    $("#scanInput").focus().select();
  } else {
    // prepend another result item
    var inputMethod = isScannerInput() ? "Scanner" : "Keyboard";
    $("#resultsList").prepend("<div class='resultItem " + inputMethod + "'>" +
      "<span>Value: " + $("#scanInput").val() + "<br/>" +
      "<span>ms/char: " + ((inputStop - inputStart) / $("#scanInput").val().length) + "</span></br>" +
      "<span>InputMethod: <strong>" + inputMethod + "</strong></span></br>" +
      "</span></div></br>");
    $("#scanInput").focus().select();
    inputStart = null;

    // Some transformations

    const barcodeString = $("#scanInput").val();

    const productCode = barcodeString.substring(5, 19);
    const serialNumber = barcodeString.substring(36, 46);
    const batch = barcodeString.substring(29, 34);
    const expirationDate = barcodeString.substring(21, 27);

    // AJAX calls
    $('#scanner-verify-button').click(function() {
      $.ajax({
        url: "DecodeScanner",
        type: "POST",
        data: {
          productCode: productCode,
          serialNumber: serialNumber,
          batch: batch,
          expirationDate: expirationDate,
          commandStatusCode: 0
        },
        async: true,
        success: function(data) {
          $('#pTextAreaResult').text(data);
        }
      });
    });
  }
}

$("#scanInput").focus();

HTML

<form>
    <input id="scanInput" />
    <button id="reset">Reset</button>
</form>
<br/>
<div>
    <h2>Event Information</h2> Start: <span id="startTime"></span>
    <br/>First Key: <span id="firstKey"></span>
    <br/>Last Ley: <span id="lastKey"></span>
    <br/>End: <span id="endTime"></span>
    <br/>Elapsed: <span id="totalTime"></span>

</div>
<div>
    <h2>Results</h2>

    <div id="resultsList"></div>
</div>
<div class="col-sm-12">
    <button id="scanner-verify-button" type="submit">Verify</button>
</div>

2 个答案:

答案 0 :(得分:0)

根据代码,扫描仪按钮的点击处理程序似乎已多次注册。

点击处理程序只能注册一次。

多次调用reportValues(),多次注册点击处理程序。这意味着当您按下按钮时,将调用所有点击处理程序并触发ajax请求。

您需要将click处理程序放在任何可以多次调用的函数之外。

同样根据代码,click处理程序需要访问的所有变量都应在reportValues之外声明。

答案 1 :(得分:0)

问题是块$('#scanner-verify-button').click(function() {}内的ajax调用每次reportValues()调用时都会在按钮上附加新的监听器。

我能够通过在自己的块中移动ajax调用来解决这个问题

// Check for any input changes

var productCode, serialNumber, batch, expirationDate;

$("#scanInput").on("change paste keyup", function () {
    barcodeString = $("#scanInput").val();
    productCode = barcodeString.substring(5, 19);
    serialNumber = barcodeString.substring(36, 46);
    batch = barcodeString.substring(29, 34);
    expirationDate = barcodeString.substring(21, 27);
}); 

// Ajax calls
$("#scanner-verify-button").click(function () {
    $.ajax({
        url: "DecodeScanner",
        type: "POST",
        data: {
            productCode: productCode,
            serialNumber: serialNumber,
            batch: batch,
            expirationDate: expirationDate,
            commandStatusCode: 0
        },
        async: true,
        success: function (data) {
            $('#pTextAreaResult').text(data);
        }
    });
});

工作Fiddle