javascript - div 标签未更新

标签 javascript jquery html function

我创建了一个连接到 REST API 的简单应用程序,如下所示:

  <!DOCTYPE html>
  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
   <script src="http://code.jquery.com/jquery-latest.min.js" >
   </script>
   <title></title>
   </head>
   <body>
    <h1 id="header">A headline</h1>
       <div id = "info"></div>
       <p1 id = "p1">p1</p1>
    <form id="name" name="name">
        Please enter a switch: <input type="text" name="switch" id = "switch">
        <input type="submit" value="submit" name="submit" id="submit">
    </form>

   <script>
        $(document).ready(function() {
            $('#name').submit(function() {
                alert('submitted');
                var switchName = $('#switch').val();
                $.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches(data));
            });
        });


       function processSwitches(data) {
        alert('processSwitches');
        var infoHTML = '<p>Switch Name: ' + data.switchName +'</p>' ;
        alert(infoHTML);
        $('#info').html(infoHTML);
        $('#header').html('<h1>Switches</h1>');
       }
   </script>
   </body>
   </html>

它运行,并将正确返回带有 infoHTML 字符串的警报,但我不明白为什么它不会更新带有 id info 的 div 标签.

有人可以帮忙吗?

谢谢。

最佳答案

您正在调用 $.getJSON 函数内的 processSwitches 函数。您应该仅传递该函数的名称 - 没有 (data) 部分:

$.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches);

简单来说,就是这样:

processSwitches

而不是这个:

processSwitches(data)

编辑:

您还忘记阻止表单提交。只需在 submit 事件处理程序末尾添加 return false 即可:

$('#name').submit(function() {
    alert('submitted');
    var switchName = $('#switch').val();
    $.getJSON('http://localhost:8081/withindex/switch','name='+switchName, processSwitches);

    return false;
});

关于javascript - div 标签未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20522058/

相关文章:

javascript - 检测歌曲结束 - SoundJS

javascript - 更漂亮的 shell 脚本格式

Javascript:获取 SharePoint Web 部件 - 要在页面上显示的对象

javascript - 为什么 data-amp-bind-href 或 [href] 在 amp-bind 组件中不起作用?

html - 防止 Visual Studio Code 将某些标记格式化为新行

javascript - jQuery JSON API 调用不起作用?

javascript - 检查按钮值jquery

jQuery 主体淡入

javascript - 如何在进一步执行 js 之前从循环中收集 $.get 的所有结果

php - css3 多个背景图片在移动时淡入淡出