angularjs AJAX 成功数据显示未定义

p5fdfcr1  于 2023-02-28  发布在  Angular
关注(0)|答案(2)|浏览(149)

我返回一个数组对象数据 AJAX 成功结果,然后打印li标记,但其显示未定义
我的 AJAX 代码是

$.ajax({
        'method': 'GET',
        'url': base_url +'party/selectCities?id='+state, 
        success: function(data) {
            var newData = data.replace(/\"/g, "")
            if(newData == ""){
            }else{
                var datas = JSON.stringify(newData);
                var jsdata = JSON.parse(datas);
                alert(jsdata);
                var html = ``;
                for(var i = 0; i<jsdata.length; i++){    
                    html += '<li ng-click="selectcityclubs(' + jsdata[i].city+ ');>' + jsdata[i].city+ '</li>';
                    }

                    $("#ClubCity").html(html);
            }
        }
});

在这里,我警告jsdata我得到如下结果

[{city:North Goa},{city:South Goa}]

但列表显示未定义,如何解决此问题
请帮我解决这个问题

wribegjk

wribegjk1#

看起来ng-click后面缺少一个双引号。请查看下面的代码片段。
此外,使用模板文字(反引号)而不是使用+来连接字符串有助于使内容更具可读性。
编辑:更新了Angular ,并展示了如何使用ng-repeatplain HTMLjQuery进行比较

// angular code
angular.module('app', [])
  .controller('TestController', function($scope) {
    $scope.selectcityclubs = function(c) {
      alert(c);
    }

    $scope.jsdata = [{
      city: 'North Goa'
    }, {
      city: 'South Goa'
    }];
  });


// jQuery code 
let jsdata = [{
  city: 'North Goa'
}, {
  city: 'South Goa'
}];

let html = '';
for (var i = 0; i < jsdata.length; i++) {
  html += `<li ng-click="selectcityclubs('${jsdata[i].city}');">${jsdata[i].city}</li>`;
}

$("#ClubCity").html(html);
li,
button {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body ng-app="app" ng-controller="TestController">
  <h2>Uses jQuery (working)</h2>
  <ul id="ClubCity"></ul>
  <h2>Click Works</h2>
  <ul id="ClubCity1">
    <li><button ng-click="selectcityclubs('North Goa')">North Goa</button></li>
    <li><button ng-click="selectcityclubs('South Goa')">South Goa</button></li>
  </ul>
  <h2>Uses ng-repeat (working)</h2>
  <ul id="ClubCity2">
    <li ng-repeat="city in jsdata" ng-click="selectcityclubs(city.city);">{{city.city}}</li>
  </ul>
</body>
oxf4rvwz

oxf4rvwz2#

对ng-click属性使用双引号(“),并使用反斜杠()转义其中的双引号

var html = '';
for (var i = 0; i < jsdata.length; i++) {
  html += '<li ng-click="selectcityclubs(\'' + jsdata[i].city + '\')">' + jsdata[i].city + '</li>';
}
$("#ClubCity").html(html);

相关问题