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 –
- Is there a simple way to trace what is happening with the
request.open()call? - Will the
XMLHttpRequest()object even work in an ASP.NET MVC application? - Will I have to make changes to the Global.asax file (or other changes) to make this work?
- 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?
(NOTE: I am trying to do this without jQuery)
Thanks very much!
You’re setting the callback to
onreadystatechangeto the result of executingcheckData. Setonreadystatechangeequal tocheckDatainstead and you should be good to go:As for your other questions:
Use Firebug or the development tool of your choice to inspect AJAX requests.
Yes, it’ll work fine.
Not that I’m aware of.
Maybe? It really depends on your routing rules and how you have IIS configured.