2016-10-17 17 views
0

javascriptを初めて使用しています。私は都市と郵便番号に基づいて医者を探すフォームを持っています。しかし、都市が落ち込んだ場合、エラーを表示する特定の都市が1つあります。なぜ特定の都市でJSONエラーが発生するのかわかりません。私が考えることができるのは、値が渡されたとき、隠された値がある場合だけです。JSONの予期しないトークンが位置250にあります

SyntaxError: Unexpected token in JSON

次のコードです:

<div class="form-group"> 
     <SELECT name="proCity" class="form-control" id="city" placeholder="City" ng-model="searchParam.City"> 
        <option disabled="disabled" selected="selected" value="">City</option> 
         <option value=""></option> 
         <cfoutput query="cityFind"> 
         <option value=#trim(city)#>#trim(city)#</option> 
        </cfoutput> 
        </select> 

     <!---<select class="form-control" id="city" ng-model="searchParam.City"><option disabled="disabled" selected="selected" value="">City</option><option ng-repeat="c in Cities">{{c.City}}</option> </select>---> 
     </div> 

    $scope.GetCityList = function(){ 
     try{ 
      $http.get("/includes/remote/ReturnCityList.cfm") 
       .then(function(response){ 
        $scope.Cities = response.data.Cities; 
       }) 
     } 
     catch(err){} 
    } 

次それは都市が含まれているテーブルを検索ところColdFusionである:

<cfoutput> 
<cftry> 
    <cfquery name="Cities" datasource="W"> 
     declare @tmpTable table (col1 nvarchar(255)) 

     insert into @tmpTable 
     select distinct city 
     from providerWeb_Multiple 
     where isnull(city,'') <> '' 
     order by city 

     declare @tmp nvarchar(max) = '' 

     select @tmp = RTRIM(LTRIM(@tmp)) 
       + ',{"value":"' + col1 + '"}' 
     from @tmpTable 

     select '{"Cities":[' + stuff(@tmp,1,1,'') + ']}' as col 
    </cfquery> 
    <cfoutput> 
     #Cities.col# 
    </cfoutput> 
    <cfcatch type="Any"> 
     <!---<cfoutput>#cfcatch.Message#<br /> 
     #cfcatch.Detail#</cfoutput>---> 
     <cfoutput>An error has been detected. Please contact us with this problem. Thanks!</cfoutput> 
    </cfcatch> 
</cftry> 

すべてのヘルプ感謝されます。

UPDATE

さて、もう少しテストの後、渡される特殊文字はありません。私はそれが私はそれが問題になる可能性がありますが、再び、私はそれを見ることはありません作成し、以下のjsファイルに関係してい信じる:

(
function(){ 
    var $scope, $location; 
    var indexApp = angular.module('indexApp',['ui.bootstrap']); 

    indexApp.controller('IndexController',function($scope,$http,$location,anchorSmoothScroll){ 
     $scope.Lang = 'initVal'; 
     $scope.ShowResults = false; 
     $scope.ShowDesc = true; 
     $scope.NoResults = false; 
     $scope.currentPage = 1; 
     $scope.maxPageNumbersToShow = 10; 
     $scope.formModel = {}; 
     $scope.searchMode = 0; 
     $scope.miles = [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }]; 
     $scope.Specialties = [{'value':'Family practice'},{'value':'General practice'},{'value':'Internal medicine'},{'value':'Pediatrics'}]; 
     $scope.Gender = [{'value':'Male'},{'value':'Female'}]; 
     $scope.Languages = {}; 
     $scope.Cities = {}; 
     $scope.searchParam = {}; 
     $("input").removeAttr('disabled'); 

     $scope.searchParam.Distance = $scope.miles[0]; 

     $scope.GetCurrentZip = function(){ 
      try{ 
       var lon, lat; 
       // console.log('starting geoposition code.'); 
       if("geolocation" in navigator){ 
        window.navigator.geolocation.getCurrentPosition(function(pos){ 
         lat = pos.coords.latitude.toFixed(3); 
         lon = pos.coords.longitude.toFixed(3); 
         // console.log(lat + ' ' + lon); 
         $http.get("/includes/remote/ReturnCurrentZipcode.cfm?Lat=" + lat + "&Lon=" + lon) 
         .then(function(response){ 
          $scope.searchParam.Zip = response.data; 
         }) 
        }) 
       } 
       else{ console.log('No geolocation'); } 
      } 
      catch(err) { console.log(err.message); } 
     } 

     $scope.GetCityList = function(){ 
      try{ 
       $http.get("/includes/remote/ReturnCityList.cfm") 
        .then(function(response){ 
         $scope.Cities = response.data.Cities; 
        }) 
      } 
      catch(err){} 
     } 

     $scope.GetLangList = function(){ 
      try{ 
       $http.get("/includes/remote/ReturnLangList.cfm") 
        .then(function(response){ 
         $scope.Languages = response.data.Languages; 
        }) 
      } 
      catch(err){} 
     } 

     $scope.SearchProvider = function(searchParam){ 
      try{ 
       $scope.searchMode = 1; 
       var queryString=''; 
       if($scope.formModel && $scope.formModel !== searchParam){ 
        $scope.resultsCount = 0; 
        currentPage = 1; 
       } 
       if(searchParam){ 
        $scope.formModel = searchParam; 
        for(var param in searchParam){ 
         if(searchParam.hasOwnProperty(param)){ 
          var paramValue = searchParam[param].value ? searchParam[param].value.trim() : searchParam[param].trim(); 
          if (paramValue.length > 0) 
           queryString += param + '=' + paramValue + '&'; 
         } 
        } 
       } 
       console.log(queryString); 
       queryString= '?' + queryString + 'currentpage=' + $scope.currentPage; 

       $http.get("/includes/remote/ReturnProvidersList.cfm" + queryString) 
       .then(function(response){ 
        $scope.providers = response.data.provider; 
        $scope.resultsCount = response.data.rowCount; 
        if (!$scope.providers){ 
          $scope.NoResults = true; 
          $scope.ShowResults = false; 
          $scope.ShowDesc = false; 
         } 
        else{ 
          $scope.NoResults = false; 
          $scope.ShowResults = true; 
          $scope.ShowDesc = false; 
         } 
       }) 
      } 
      catch(err){ alert('No response.: ' + err.message); } 
     } 

     $scope.$watchGroup(['currentPage'], function(){ 
      try{ 
       if($scope.searchMode == 1){ 
        $scope.SearchProvider($scope.formModel); 
        } 
      } 
      catch(err){} 
     }); 


     $scope.GetCityList(); 
     $scope.GetLangList(); 
     $scope.GetCurrentZip(); 

     $scope.gotoElement = function (eID){ 
      //http://jsfiddle.net/brettdewoody/y65G5/ 
       // set the location.hash to the id of 
       // the element you wish to scroll to. 

      //$location.hash('bottom'); 

       // call $anchorScroll() 
      var browserWidth = screen.availWidth; 
      if (browserWidth < 768) 
       anchorSmoothScroll.scrollTo(eID); 
     }; 

    }); 

    indexApp.service('anchorSmoothScroll', function(){ 
     this.scrollTo = function(eID) { 

      // This scrolling function 
      // is from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript 

      var startY = currentYPosition(); 
      var stopY = elmYPosition(eID); 
      var distance = stopY > startY ? stopY - startY : startY - stopY; 
      if (distance < 100) { 
       scrollTo(0, stopY); return; 
      } 
      var speed = Math.round(distance/100); 
      if (speed >= 20) speed = 20; 
      var step = Math.round(distance/25); 
      var leapY = stopY > startY ? startY + step : startY - step; 
      var timer = 0; 
      if (stopY > startY) { 
       for (var i=startY; i<stopY; i+=step) { 
        setTimeout("window.scrollTo(0, "+leapY+")", timer * speed); 
        leapY += step; if (leapY > stopY) leapY = stopY; timer++; 
       } return; 
      } 
      for (var i=startY; i>stopY; i-=step) { 
       setTimeout("window.scrollTo(0, "+leapY+")", timer * speed); 
       leapY -= step; if (leapY < stopY) leapY = stopY; timer++; 
      } 

      function currentYPosition() { 
       // Firefox, Chrome, Opera, Safari 
       if (self.pageYOffset) return self.pageYOffset; 
       // Internet Explorer 6 - standards mode 
       if (document.documentElement && document.documentElement.scrollTop) 
        return document.documentElement.scrollTop; 
       // Internet Explorer 6, 7 and 8 
       if (document.body.scrollTop) return document.body.scrollTop; 
       return 0; 
      } 

      function elmYPosition(eID) { 
       var elm = document.getElementById(eID); 
       var y = elm.offsetTop; 
       var node = elm; 
       while (node.offsetParent && node.offsetParent != document.body) { 
        node = node.offsetParent; 
        y += node.offsetTop; 
       } return y; 
      } 

     }; 

    }); 

    indexApp.directive('allowPattern',[allowPatternDirective]); 
    indexApp.directive('popPopup',[describePopup]); 
    indexApp.directive('pop', function pop ($tooltip, $timeout) { 
    var tooltip = $tooltip('pop', 'pop', 'event'); 
    var compile = angular.copy(tooltip.compile); 
    tooltip.compile = function (element, attrs) {  
     var first = true; 
     attrs.$observe('popShow', function (val) { 
     if (JSON.parse(!first || val || false)) { 
      $timeout(function(){ 
       element.triggerHandler('event'); 
      }); 
      } 
      first = false; 
     }); 
     return compile(element, attrs); 
     }; 
     return tooltip; 
    }); 

    indexApp.filter('PhoneNumber', function(){ 
    return function(phoneNumber){ 
     var dash = '-'; 
     var openParen = '('; 
     var closeParen = ') '; 
     if(phoneNumber){ 
      var pn = phoneNumber; 
      pn = [pn.slice(0, 6), dash, pn.slice(6)].join(''); 
      pn = openParen + [pn.slice(0, 3), closeParen, pn.slice(3)].join(''); 
      return pn; 
      } 
     return phoneNumber; 
     } 
    }); 

    indexApp.filter('Zip', function(){ 
    return function(zipcode){ 
     var dash = '-'; 
     if(zipcode && zipcode.length > 5){ 
      var zc = zipcode; 
      zc = [zc.slice(0, 5), dash, zc.slice(5)].join(''); 
      return zc; 
      } 
     return zipcode; 
     } 
    }); 

    function allowPatternDirective(){ 
     return{ 
      restrict: "A", 
      compile: function(tElement, tAttrs){ 
       return function(scope, element, attrs){ 
        element.bind("keypress", function(event){ 
         var keyCode = event.which || event.keyCode; 
         var keyCodeChar = String.fromCharCode(keyCode); 

         if(!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))){ 
          event.preventDefault(); 
          return false; 
         } 
        }); 
       } 
      } 
     } 
    } 

    function describePopup(){ 
     return { 
      restrict: 'EA', 
      replace: true, 
      scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' }, 
      templateUrl: 'template/popover/popover.html' 
      }; 
     } 
})(); 
(function($) { 
    // @todo Document this. 
    $.extend($,{ placeholder: { 
     browser_supported: function() { 
     return this._supported !== undefined ? 
      this._supported : 
      (this._supported = !!('placeholder' in $('<input type="text">')[0])); 
     }, 
     shim: function(opts) { 
     var config = { 
      color: '#888', 
      cls: 'placeholder', 
      selector: 'input[placeholder], textarea[placeholder]' 
     }; 
     $.extend(config,opts); 
     return !this.browser_supported() && $(config.selector)._placeholder_shim(config); 
     } 
    }}); 

    $.extend($.fn,{ 
    _placeholder_shim: function(config) { 
     function calcPositionCss(target) 
     { 
     var op = $(target).offsetParent().offset(); 
     var ot = $(target).offset(); 

     return { 
      top: ot.top - op.top, 
      left: ot.left - op.left, 
      width: $(target).width() 
     }; 
     } 
     function adjustToResizing(label) { 
     var $target = label.data('target'); 
     if(typeof $target !== "undefined") { 
      label.css(calcPositionCss($target)); 
      $(window).one("resize", function() { adjustToResizing(label); }); 
     } 
     } 
     return this.each(function() { 
     var $this = $(this); 

     if($this.is(':visible')) { 

      if($this.data('placeholder')) { 
      var $ol = $this.data('placeholder'); 
      $ol.css(calcPositionCss($this)); 
      return true; 
      } 

      var possible_line_height = {}; 
      if(!$this.is('textarea') && $this.css('height') != 'auto') { 
      possible_line_height = { lineHeight: $this.css('height'), whiteSpace: 'nowrap' }; 
      } 

      var isBorderBox = ($this.css('box-sizing') === 'border-box'); 
      var isTextarea = $this.is('textarea'); 

      var ol = $('<label />') 
      .text($this.attr('placeholder')) 
      .addClass(config.cls) 
      .css($.extend({ 
       position:'absolute', 
       display: 'inline', 
       'float':'none', 
       overflow:'hidden', 
       textAlign: 'left', 
       color: config.color, 
       cursor: 'text', 
       paddingTop: !isTextarea && isBorderBox ? '0' : $this.css('padding-top'), 
       paddingRight: $this.css('padding-right'), 
       paddingBottom: !isTextarea && isBorderBox ? '0' : $this.css('padding-bottom'), 
       paddingLeft: $this.css('padding-left'), 
       fontSize: $this.css('font-size'), 
       fontFamily: $this.css('font-family'), 
       fontStyle: $this.css('font-style'), 
       fontWeight: $this.css('font-weight'), 
       textTransform: $this.css('text-transform'), 
       backgroundColor: 'transparent', 
       zIndex: 99, 
      }, possible_line_height)) 
      .css(calcPositionCss(this)) 
      .attr('for', this.id) 
      .data('target',$this) 
      .click(function(){ 
       if (!$(this).data('target').is(':disabled')) { 
        $(this).data('target').focus(); 
       } 
      }) 
      .insertBefore(this); 
      $this 
       .data('placeholder', ol) 
       .on('keydown', function() { 
        ol.hide(); 
       }) 
       .on('blur change', function() { 
        ol[$this.val().length ? 'hide' : 'show'](); 
       }) 
       .triggerHandler('blur'); 
      $(window).one("resize", function() { adjustToResizing(ol); }); 
     } 
     }); 
    } 
    }); 
})(jQuery); 

jQuery(document).add(window).bind('ready load', function() { 
    if (jQuery.placeholder) { 
    jQuery.placeholder.shim(); 
    } 
}); 

UPDATE @Leighによって示唆されるように、私は自分のベストを試してみました主な問題に集中し、結果を生成するコードを選択します。

次のコードでは、都市を表示するために使用されているものです。

<div class="form-group"> 
     <SELECT name="proCity" class="form-control" id="city" placeholder="City" ng-model="searchParam.City"> 
        <option disabled="disabled" selected="selected" value="">City</option> 
         <option value=""></option> 
         <cfoutput query="cityFind"> 
         <option value=#trim(city)#>#trim(city)#</option> 
        </cfoutput> 
        </select> 

     <!---<select class="form-control" id="city" ng-model="searchParam.City"><option disabled="disabled" selected="selected" value="">City</option><option ng-repeat="c in Cities">{{c.City}}</option> </select>---> 
     </div> 

次は私がデータベースに値を渡すと、結果を取得するために使用していますJSファイルです:

function(){ 
    var $scope, $location; 
    var indexApp = angular.module('indexApp',['ui.bootstrap']); 

    indexApp.controller('IndexController',function($scope,$http,$location,anchorSmoothScroll){ 
     $scope.Lang = 'initVal'; 
     $scope.ShowResults = false; 
     $scope.ShowDesc = true; 
     $scope.NoResults = false; 
     $scope.currentPage = 1; 
     $scope.maxPageNumbersToShow = 10; 
     $scope.formModel = {}; 
     $scope.searchMode = 0; 
     $scope.miles = [{'value':'5'},{'value':'10'},{'value':'15'},{'value':'20' }]; 
     $scope.Specialties = [{'value':'Family practice'},{'value':'General practice'},{'value':'Internal medicine'},{'value':'Pediatrics'}]; 
     $scope.Gender = [{'value':'Male'},{'value':'Female'}]; 
     $scope.Languages = {}; 
     $scope.Cities = {}; 
     $scope.searchParam = {}; 
     $("input").removeAttr('disabled'); 
$scope.GetCityList = function(){ 
      try{ 
       $http.get("/includes/remote/ReturnCityList.cfm") 
        .then(function(response){ 
         $scope.Cities = response.data.Cities; 
        }) 
      } 
      catch(err){} 
     } 

次はReturnCityList.cfmファイルです:

<cftry> 
    <cfquery name="Cities" datasource="Wa"> 
     declare @tmpTable table (col1 nvarchar(255)) 

     insert into @tmpTable 
     select distinct city 
     from providerWeb_Multiple 
     where isnull(city,'') <> '' 
     order by city 

     declare @tmp nvarchar(max) = '' 

     select @tmp = RTRIM(LTRIM(@tmp)) 
       + ',{"value":"' + col1 + '"}' 
     from @tmpTable 

     select '{"Cities":[' + stuff(@tmp,1,1,'') + ']}' as col 
    </cfquery> 
    <cfoutput> 
     #Cities.col# 
    </cfoutput> 
    <cfcatch type="Any"> 
     <!---<cfoutput>#cfcatch.Message#<br /> 
     #cfcatch.Detail#</cfoutput>---> 
     <cfoutput>An error has been detected. Please contact us with this problem. Thanks!</cfoutput> 
    </cfcatch> 
</cftry> 
+3

私の推測では、エスケープする必要がある特殊文字が値の一部に含まれています。独自のJSONをロールしないでください。代わりに[serializeJSON](https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-s/serializejson.html)(いくつかの癖があります)またはそこにある既存のJSONライブラリの1つを使用してください。 – Leigh

+0

@Leigh自分のJSONを使用していません。私はangular.min.js verを使用しています。 1.4.4 –

+0

Angleの未使用バージョンを使用してJSONに変換しているものを検査できるように、ブレークポイントを追加してみましょう。'{ "都市":[' +もの(TMP、1,1 @、 '')+ ']}' のようにあなたがあなたのクエリ... 'を選択して、それを作成している、あなた自身のJSONを使用している – olan

答えて

-1

たぶん、あなたのJSON STR

8233行区切り文字 - - 段落区切り

8232:インラインJSONとして送達されたときINGは、このテストが終了し、いくつかの無効なUnicodeの文字

が含まれている、私は問題があることが 文字以下のASCIIコントロールを見つけました実際のSTRを見ずに

https://www.bennadel.com/blog/2576-testing-which-ascii-characters-break-json-javascript-object-notation-parsing.htm

関連する問題