在JavaScript中匹配10个数字并进行Ajax调用

时间:2017-04-22 05:42:10

标签: javascript jquery ajax regex

我想创建这个功能:

  • 如果ID为10位,则应对文件号1进行ajax调用
  • 如果ID为18位,则应对其他文件进行ajax调用

以下是代码:

function get_invoice_info(expressid,expressno,div_id)
{
    document.getElementById("retData")
       .innerHTML="<center>Please wait fetching tracking details for you...</center>";

    var expressno = '{$order.invoice_no}';
    var matches = expressno.match(/^\d{12}$/);

    Ajax.call('plugins/track/tracking.php?CN='+ expressno,
        'showtest=showtest', 
        function(data){
            document.getElementById("retData").innerHTML=data;
        }, 
        'GET', 
        'TEXT'
    );

    } else {
      Ajax.call('plugins/track/tracking.php?CN='+ expressno,
         'showtest=showtest', 
         function(data) {
             document.getElementById("retData").innerHTML=data;
         }, 
         'GET', 
         'TEXT'
      );    
   }

此代码正如我希望的那样工作

function get_invoice_info(expressid,expressno,div_id)
{
    var waitMsg = "Please wait fetching tracking details for you...";
    document.getElementById("retData").innerHTML= waitMsg;
    var expressno = '{$order.invoice_no}';
    if(expressno.length === 12) {
    filePath='tracking';
    } else if(expressno.length === 18) {   
    filePath='track';
    } else {
    //Not in range, so exit
    return;
  }
    Ajax.call('plugins/track/'+filePath+'.php?CN='+ expressno, 'showtest=showtest', function(data){document.getElementById("retData").innerHTML=data;}, 'GET', 'TEXT');

}

1 个答案:

答案 0 :(得分:0)

我错过了什么,好像你只能检查长度(或者它只需要数字,在这种情况下你可以在开头添加另一个if语句来检查非数字字符)。

function get_invoice_info(expressid,expressno,div_id) {
  var waitMsg = "Please wait fetching tracking details for you...";
  var expressno = '{$order.invoice_no}';
  var filePath = null;

  document.getElementById("retData").innerHTML= waitMsg;

  if(expressno.length === 10) {
    filePath='file1';
  } else if(expressno.length === 16) {   
    filePath='file2';
  } else {
    //Not in range, so exit
    return;
  }
  var onSuccess = function(data){
      document.getElementById("retData").innerHTML=data;
  };
  Ajax.call('plugins/track/'+filePath+'.php?CN='+ expressno,
     'showtest=showtest', 
     onSuccess, 
     'GET', 
     'TEXT'
);