Call a URL and get the return value. both Jquery and Javascript doesnt display the return value [duplicate]
Possible Duplicate:
XMLHttpRequest.responseText doesnt write the value when calling a URL
I ve written the code in both javascript and jquery to call a URL and get the return value by referring here and here.
But the return value of the aspx page doesnt get displayed in my html file. Since I am new to javascript and jquery, can you please let me know if I need to put a call back as its cross posting? if so, can you explain me?
The Javascript code is
<script type="text/javascript" >
var req ;
// Browser compatibility check
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
var req = new XMLHttpRequest();
req.open("GET", "http://www.example.com/Default.aspx?usrname=john",true);
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
req.send(null);
</script>
</开发者_开发知识库script>
<html>
<head/>
<body>
<div id="divTxt"></div></body>
</html>
The output I get is : My Status :
The JQuery code is
var html = $.ajax({
url: "http://www.example.com/Default.aspx?usrname=john",
async: true
}).responseText;
document.getElementById('divTxt').innerHTML = "My Status: " + html;
The output I get is blank page
PS: I am reposting the question again as my question was not answered properly before.
**
> EDIT: in my original code, there is
http://
**
You cannot ajax a url from another domain unless it has implemented CORS
If you need to get data from somewhere which is not same origin you need to use JSONP
Also to debug, try calling the url from the locationbar to see if you receive valid data for your request
you are doing several things incorrectly.
First, you're overwriting your req variable (which you initialize for different browsers up on top). So, remove this line: var req = new XMLHttpRequest();
Next you're calling a url that is at a different domain than yours which AJAX security won't let you. Also you're forgetting to include http:// but that is besides the point since you're not allowed to leave your own domain, and lastly you're calling onReadyState change but failing to note the readyState which will go through several stages. You're looking for stage 4 to actually do something with.
精彩评论