有可能是在我的code的一个小错误。请咨询我。
我要调用一个URL和DIV显示值在pageload.I写了这code从SO但responseText的犯规写的div元素的innerHTML值
code
<脚本类型=文/ JavaScript的>
VAR REQ;
//浏览器兼容性检查
如果(window.XMLHtt prequest){
REQ =新XMLHtt prequest();
}否则,如果(window.ActiveXObject){
尝试 {
REQ =新的ActiveXObject(MSXML2.XMLHTTP);
}赶上(五){
尝试 {
REQ =新的ActiveXObject(Microsoft.XMLHTTP);
}赶上(五){}
}
}
VAR REQ =新XMLHtt prequest();
req.open(GET,www.example.com/Default.aspx?usrname=john",true);
req.onreadystatechange =功能(){
的document.getElementById('divTxt)的innerHTML =我的状态。+ req.responseText;
}
req.send(空);
< / SCRIPT>
< HTML>
<头/>
<身体GT;
< DIV ID =divTxt>< / DIV>< /身体GT;
< / HTML>
我得到的输出 我的状态:
PS:我想这页面加载后进行,网址返回一个值联机手动调用时
修改 这是code我简称: code
解决方案您不能从另一个域阿贾克斯的URL,除非它已经实施的 CORS
如果你需要从一个地方是不能得到数据的同根同源的,你需要使用的 JSONP
另外需要调试,尝试调用从locationbar的网址,看看您收到的有效数据,您的要求
There may be a small error in my code. please advice me.
I want to call a URL and display the value in div on pageload.I wrote this code from SO but the responseText doesnt write the value in the div element's innerhtml
Code
<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", "www.example.com/Default.aspx?usrname=john",true);
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
req.send(null);
</script>
<html>
<head/>
<body>
<div id="divTxt"></div></body>
</html>
The output I get is My status :
PS: I want this to be done after pageload and The url returns a value "online" when called manually
EDIT This is the code I referred : code
解决方案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