سؤال

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. But I can't figure out why it won't populate my div area.

<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 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.

Second, you are using jQuery but then switch back to classic 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.

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. 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:

<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>

If you want to change the contend of div not using jquery, you should use innerHTML instead of value.

document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top