我创建了一个连接到 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/