[英]Issue populating ajax response into a div
What am I missing? 我想念什么? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. 我已经通过Id添加了get元素,并且肯定会得到响应,我使用firebug检查了响应是否正确。 But I can't figure out why it won't populate my div area. 但我不知道为什么它不会填充我的div区域。
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in: 我希望将Div放入响应中:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal. 首先,您正在调用document.getElementById(),但是您的div没有终端ID,它有一个名为terminal的类。
Second, you are using jQuery but then switch back to classic JavaScript. 其次,您正在使用jQuery,但随后又切换回经典JavaScript。 You could update your code to the following: 您可以将代码更新为以下内容:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName")
selector is for selecting by class and $("#SomeName")
is to select by id. 请注意, $(".SomeName")
选择器用于按类选择, $("#SomeName")
选择器用于按ID选择。
Edit and Note 编辑和注释
If this terminal div could start to get a lot of data inside of it, you may look at using the .append()
function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. 如果此终端div可以开始在其中获取大量数据,则可以考虑使用jQuery中的.append()
函数来避免必须复制HTML并在每次发出请求时覆盖HTML。 The update would be something similar to the following (its a little shorter and should be more efficient as well) 此更新将类似于以下内容(它稍短一些,并且应该也更有效)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div: 如果要通过id获取元素,请向div添加一个id:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
如果要不使用jquery更改div的内容,则应使用innerHTML而不是value。
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.