Can I use this Ajax script to communicate and exchange data between client and server?
This block of code is for client.html (it is located in this www.client.com/client.html) - client side.
The I have the code below that goes something like this:
ajaxRequest.open("GET", "http://www.se开发者_如何学Crver.com/ajax.php", true);
This is how I call the file ajax.php located in the server. Unfortunately I have no luck at all. It cannot connect to the server I'm calling. BTW, the ips /test site I've been using are all no restrictions, and is accessible to all.
However, I tried to simulate by putting both client.html and ajax.php in same site and it works well.
So my question is does this script works only if you are in same site? or does it work also in client-server scenario? What else do I have to do in order to make this work?
//client.html
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "http://www.server.com/ajax.php", true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
// ajax.php
<?php
echo date("H:i:s");
?>
Browser follow the same origin policy for security reasons. So you will not be able to make an AJAX request to a different domain.
If you have control to the server, you can send special headers that allows cross-domain AJAX. Otherwise I think you have to find different methods.
Another thing you can do is to add a script to your page, whose source resides on www.server.com. Then in the source you can transmit data, for instance by assigning it to a new variable. In this way you are not constrained by cross-domain restrictions, but will only be able to do a GET request (not POST, PUT, DELETE...). Moreover there needs to be some collaboration from the server. Unlike in AJAX requests, the server will not spit out any page, but has to output valid javascript.
Usually the server actually encodes the data in JSON, and passes it to a given function, so the response may look like
someCallback({foo: 'bar', bar: 'foo'});
This techique is called JSONP, and you can find more details here.
精彩评论