I am running MongoDB in the REST mode and trying to get query results from the MongoDB server through HTTP request. The following is the simple code that I have written:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function httpGet(theUrl){
//document.write(theUrl);
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUr开发者_C百科l, false);
xmlHttp.send(null);
document.getElementById("response").innerHTML=xmlHttp.responseText;
}
</script>
<title>Connection</title>
</head>
<body>
<button onclick="httpGet('http://127.0.0.1:28017/test/first/?limit=-1')" >
Click
</button>
<p id="response"> </p>
</body>
</html>
But I am unable to get the response. Whereas when I copy and paste the URL in the address bar of the browser I get following as the response:
{
"offset" : 0,
"rows": [
{ "_id" : { "$oid" : "4d510086ce29000000007d5a" }, "date" : { "$date":60968917800000 } }
],
"total_rows" : 1 ,
"query" : {} ,
"millis" : 0
}
Can someone help and tell me what could be the problem.
Is the page on which your code is running also loaded from 127.0.0.1 port 28017? If not, that's your problem, you're running into the Same Origin Policy.
If it is (both server and port are the same), I'd recommend using a relative URL, so your
httpGet('http://127.0.0.1:28017/test/first/?limit=-1')
becomes
httpGet('/test/first/?limit=-1')
Fundamentally, the code works: http://jsbin.com/awose3
Off-topic: I'd strongly recommend not using synchronous XHR calls (ajax requests). They lock up the UI of the browser while they're in process, and of course they can take a second or two (or ten) to run, during which the user experience is unpleasant to say the least. Instead, use an asynchronous call and a callback on onreadystatechange
, like this (obviously, error handling and other complexities have been left out):
function httpGet(theUrl){
//document.write(theUrl);
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, true);
xmlHttp.onreadystatechange = handleReadyStateChange;
xmlHttp.send(null);
function handleReadyStateChange() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById("response").innerHTML=xmlHttp.responseText;
}
}
}
}
Live example
Off-topic 2: I'd suggest looking at a library like jQuery, Prototype, YUI, Closure, or any of several others. They'll smooth over browser quirks, simplify various things, and add a number of useful features so that you can concentrate on solving the actual problem you're trying to solve, rather than worrying about things like (random example) Safari mis-reporting the default selected value of an option
, and Internet Explorer's habit of leaking memory on event handlers unless you chant, burn incense, and periodically get up and twirl three times as you write your code.
精彩评论