我在寻找一个非常小的(单行)的Ajax JavaScript库中添加的一个小剧本的第一线做出一些要求。
I'm looking for a very small (one liner) Ajax JavaScript library to add on the first line of a small script to make some requests.
我已经尝试过:
-
JX
Microajax
但他们并没有在所有的工作。替代方案?
But they do not work at all. Alternatives?
推荐答案在这里你去,pretty的简单:
Here you go, pretty simple:
function createXHR() { var xhr; if (window.ActiveXObject) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { alert(e.message); xhr = null; } } else { xhr = new XMLHttpRequest(); } return xhr; }
文件是这里
例如:
var xhr = createXHR(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { alert(xhr.responseText); } } xhr.open('GET', 'test.txt', true) xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.send()
更新:
为了做跨域脚本,你要么不得不叫出到本地服务器端代理(读取和Echo的远程数据),或者,如果远程服务返回的JSON,使用此方法:
In order to do cross-domain scripting, you'll either have to call out to a local server-side proxy (which reads and echo's the remote data), or, if your remote service returns JSON, use this method:
var s = document.createElement('script') s.src = 'remotewebservice.json'; document.body.appendChild(s);
由于JSON本质上是一个JavaScript对象或数组,这是一个有效的来源。您的理论上的应该然后就可以直接调用远程服务。我没有测试过这一点,但它似乎是一个公认的做法:
Since JSON is essentially a JavaScript object or array, this is a valid source. You theoretically should then be able to call the remote service directly. I haven't tested this, but it seems to be an accepted practice:
参考:调用跨域的Web服务中AJAX
更多推荐
小Ajax的JavaScript库
发布评论