Tyl*_*hes 5 javascript php real-time
这可能听起来很奇怪,但我一直用PHP编写游戏.我发现的主要问题是更新PHP的唯一方法是加载页面.这使得实时变慢.Javascript可以与页面交互而无需重新加载.是否可以使用Javascript在页面上加载PHP页面?这样它就可以在不重新加载的情况下反复加载PHP.
我已经看到它与聊天室完成,但不知道它是如何工作的.
我们主要使用 Ajax,它由客户端 Javascript 代码组成,无需离开页面即可调用服务器端页面。
下面是一个使用GET方法 ( JSFiddle )获取页面显示内容的示例:
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
console.log(this.responseText);
}
}
xhr.open('GET','myPHPPage.php?foo=foo&bar=bar',true);
xhr.send();
Run Code Online (Sandbox Code Playgroud)
这里使用POST方法(JSFiddle):
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
var data = 'foo=foo&bar=bar';
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
console.log(this.responseText);
}
}
xhr.open('POST','myPHPPage.php',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length',data.length);
xhr.send(data);
Run Code Online (Sandbox Code Playgroud)
请注意,这里我们使用setRequestHeader方法来更改此 HTTP 请求的标头,在本例中,更改Content-type和Content-length(此标头的默认值为 4096 字节)。另外,该setRequestHeader方法必须在该方法之后调用open。
这些链接应该可以帮助您:
https://developer.mozilla.org/en/Ajax
http://code.google.com/intl/pt-BR/edu/ajax/tutorials/ajax-tutorial.html
| 归档时间: |
|
| 查看次数: |
3156 次 |
| 最近记录: |