【问题标题】:Why is my JavaScript loop not being entered?为什么我的 JavaScript 循环没有被输入?
【发布时间】:2020-02-04 15:27:32
【问题描述】:

我有一个 JavaScript 函数,它遍历从 Java 方法接收到的数据。我可以看到正在填充数据变量,但没有进入循环;

JavaScript - 在 Web 控制台中,数据变量填充为 data=[{"id":"1","name":"Megan","pay":100.0}] Web 控制台中显示以下错误;

jquery-3.3.1.js:3963 jQuery.Deferred exception: Cannot use 'in' operator to search for 'length' in [{"id":"1","name":"Megan","pay":100.0}] TypeError: Cannot use 'in' operator to search for 'length' in [{"id":"1","name":"Megan","pay":100.0}]
    at isArrayLike (http://localhost:8080/jquery-3.3.1.js:498:33)
    at Function.each (http://localhost:8080/jquery-3.3.1.js:359:8)
    at Object.<anonymous> (http://localhost:8080/csvTest.js:10:11)
    at mightThrow (http://localhost:8080/jquery-3.3.1.js:3665:29)
    at process (http://localhost:8080/jquery-3.3.1.js:3741:12) undefined
$(document).ready(function() {
$('#test').click(function() {

     $.ajax({
            url: "/test" 
     }).then(function(data) {

        $.each(data, function (i, item) {
          console.log(item.name);
        });

        });
  });
});

返回数据的方法;

  @GetMapping("/test") 
      @ResponseBody
        public String getEmployeePercentageMatch(HttpServletRequest request, HttpServletResponse response,String roleName, String percentageMatch) throws IOException {
          percentageMatch="50";
          List<Employee> matchEmployees = new ArrayList<Employee>();
            Optional<Role> currentRole=roleRepository.findByroleNameIs("SWEM"); 
            Optional<List<RoleMapSkill>> skillsForRoles = roleMapSkillRepository.getSkillsForRole(currentRole);
            List<RoleMapSkill> skillsForRole = skillsForRoles.get();

            for(int i=0; i<skillsForRole.size(); i++) {
                Map<String, String> roleSkillMap = new HashMap<String, String>();
                roleSkillMap.put(skillsForRoles.get().get(i).getIdSkill().getIdSkill(), skillsForRoles.get().get(i).getRating());
                System.out.println(skillsForRoles.get().get(i).getIdSkill().getIdSkill()+" "+roleSkillMap.get(skillsForRoles.get().get(i).getIdSkill().getIdSkill()));
            }
            List<Employee> allEmployees = employeeRepository.findAll();
            for(int i=0; i<allEmployees.size(); i++) {
                int totalPercentage=0;
                Employee currentEmployee = allEmployees.get(i);
                Optional<List<EmployeeMapSkill>> skillEmployeeMap = employeeMapSkillRepository.getSkillsForEmployee(currentEmployee);
                for(int j=0; j<skillsForRole.size(); j++) {

                    if(skillEmployeeMap.isPresent()){
                        Map<String,String> employeeSkillMap = new HashMap<String, String>();
                        employeeSkillMap.put(skillEmployeeMap.get().get(j).getIdSkill().getIdSkill(), skillEmployeeMap.get().get(j).getRating());

                    }

                }
                for(int k=0; k<skillsForRole.size(); k++) {
                    if(skillEmployeeMap.isPresent()){
                    int individualPercentageMatch=(100/Integer.valueOf(skillsForRoles.get().get(k).getRating()))*Integer.valueOf(skillEmployeeMap.get().get(k).getRating());
                    totalPercentage= totalPercentage+individualPercentageMatch;
                    }
                }
                int totalPercentageMatch = totalPercentage/skillsForRole.size();
                System.out.println(totalPercentageMatch);

                if(totalPercentageMatch>=Integer.valueOf(percentageMatch)) {
                    matchEmployees.add(currentEmployee);
                }


            }
            String json = new Gson().toJson(matchEmployees);
            PrintWriter writer = response.getWriter();
            writer.write(json);

            return null;
        }

【问题讨论】:

  • 什么循环? $.each?
  • 是的那个循环:)
  • 只是为了检查我的理解是否正确,您希望在控制台上看到“Megan”,但您没有?
  • 没错,但是当我在 Web 控制台上的调试器中运行时,根本没有进入循环,因为我在 console.log 行上有一个断点,甚至没有运行
  • 在每个之前使用 console.log(data)。看看你得到了什么。

标签: javascript java jquery get httpresponse


【解决方案1】:

那是JQuery;我不喜欢那样,但是(在所有人的帮助下)...dataType: 'json' 被错过了

在你的代码上

    $('#test').click(function() {

     $.ajax({
            url: "/test", 
            dataType: 'json'

     }).then(function(data) {
        $.each(data, function (i, item) {
          console.log(item.name);
        });

        });
  });

但是,我不太确定……

【讨论】:

  • 有什么地方我特别应该添加那行吗?我已经添加了它; }).then(function(data) { //这里 $.each(data, function (i, item) { 但它似乎没有帮助
  • 但这是有道理的。 $.ajax 默认会根据服务器发送的Content-Type 解释data。这可能不是将它作为 json 发送。尝试将dataType: 'json' 选项(与url 一起)添加到ajax 调用
  • 我试过了,使用 JSON.parse 它抛出了一个错误,但是一旦我删除了该行,它似乎就可以工作了:)
  • 删除了我的评论,OP 准确地添加了我所说的错误(@nu7m3g 不要忘记在您的问题中包含错误,这将节省大量时间)
猜你喜欢
  • 2020-01-01
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多