Reputation: 3930
I am trying to test using the JavaScript XMLHttpRequest()
object in an ASP.NET MVC application.
I have written the following test code which I put into a View -
<script type="text/javascript">
var request;
function getAJAX() {
request = new XMLHttpRequest();
request.open("GET", "test.txt");
request.onreadystatechange = checkData();
request.send(null);
}
function checkData() {
if (request.readyState == 4) {
if (request.status == 200) {
alert(request.responseText);
}
}
}
</script>
<form action="">
<p>
<button type="button" onclick="getAJAX()">DO IT!</button>
</p>
</form>
When I click in the "DO IT!" button, the script functions get called, but the "request.onreadystatechange"
never changes.
I have a few questions about this -
request.open()
call?XMLHttpRequest()
object even work in an ASP.NET MVC application? "test.txt"
in the "base"
directory (the same location as the Global.asax file) is that where the request.open call will look?(NOTE: I am trying to do this without jQuery)
Thanks very much!
Upvotes: 0
Views: 2450
Reputation: 126052
You're setting the callback to onreadystatechange
to the result of executing checkData
. Set onreadystatechange
equal to checkData
instead and you should be good to go:
function getAJAX() {
request = new XMLHttpRequest();
request.open("GET", "test.txt");
request.onreadystatechange = checkData; // Don't execute checkData
request.send(null);
}
As for your other questions:
Is there a simple way to trace what is happening with the request.open() call?
Use Firebug or the development tool of your choice to inspect AJAX requests.
Will the XMLHttpRequest() object even work in an ASP.NET MVC application?
Yes, it'll work fine.
Will I have to make changes to the Global.asax file (or other changes) to make this work?
Not that I'm aware of.
I have "test.txt" in the "base" directory (the same location as the Global.asax file) is that where the request.open call will look?
Maybe? It really depends on your routing rules and how you have IIS configured.
Upvotes: 1