jQuery自动完成表单,工作一半的时间

时间:2014-01-03 14:21:38

标签: jquery geocoding

我有一个包含一些输入的表单,包括邮政编码字段。当用户输入他们的zip时,我使用http://www.zippopotam.us/邮政编码API来查找他们的城市和州,并将这些值放在隐藏的字段中。

当我在控制台中测试它时,它运行良好,但城市和州的价值仅在我们后端的一半时间内完成。

以下是代码:

  $(function(){

  var postalField = $('#field7');
  var alphaExp = /^[a-zA-Z]+$/; //check for alphabet characters

  //function to call zippopotamus API
  function zippopotamus(theZip){
  var country = "";
  var client = new XMLHttpRequest();
    if (!theZip[0].match(alphaExp)){ //if the zip starts with a number
      //use United States api
      client.open("GET", "http://api.zippopotam.us/us/"+theZip, true);
      country = "US";
    } else { //else if it starts with a letter
      //use Canada api
      client.open("GET", "http://api.zippopotam.us/CA/"+theZip.substring(0,3), true);
      country = "CA";
    }

  client.onreadystatechange = function() {
    if(client.readyState == 4) {
      var responseJSON = $.parseJSON(client.responseText);
      console.log(responseJSON);
      var city = responseJSON['places'][0]['place name'];
      $('#field8').val(city);
      var state = responseJSON['places'][0]['state abbreviation'];
      $('#field9').val(state);
      $('#field10').val(country);
      $('#field15').val(client.statusText);
    };
  };

  client.send();
  }

  postalField.on('blur submit',function(){
    var postalInput = postalField.val();

    if (postalInput !=0) { //if the postal code is not blank run the ajax
      zippopotamus(postalInput);
    }//end if statement
 } );

0 个答案:

没有答案