有没有办法调用网址并使用javascript获得响应?我需要相当于ASP.NET:
WebRequest req = HttpWebRequest.Create("http://someurl.com");
WebResponse webResponse = req.GetResponse();
Run Code Online (Sandbox Code Playgroud)
我有一个外部网址,其中包含我需要的一些信息,我想从javascript中调用此网址并解析响应,以确定在我的应用程序中要执行的操作.
tva*_*son 19
如果URL位于同一域中,您可以发出AJAX请求,例如,相同的主机不同的应用程序.如果是这样,我可能会使用像jQuery这样的框架,很可能是get方法.
$.get('http://someurl.com',function(data,status) {
...parse the data...
},'html');
Run Code Online (Sandbox Code Playgroud)
如果您遇到跨域问题,那么最好的办法是创建一个代理请求的服务器端操作.使用AJAX向服务器发出请求,请求服务器请求并从外部主机返回响应.
感谢@ nickf,指出我的原始解决方案存在明显问题,如果网址位于不同的域中.
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", "test.html",true);
req.onreadystatechange = function () {
//document.getElementById('divTxt').innerHTML = "Contents : " + req.responseText;
}
req.send(null);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118412 次 |
| 最近记录: |