admin管理员组

文章数量:1404923

It may sound odd, but I've been programming games in PHP. The main problem I've found was that the only way to update PHP is to load a page. That makes real-time slow. Javascript can interact with a page without reloading it. Is it possible to load PHP pages on a page using Javascript? So that it would allow PHP to be loaded over and over without reloading.

I've seen it done with Chat rooms but not sure how it works.

It may sound odd, but I've been programming games in PHP. The main problem I've found was that the only way to update PHP is to load a page. That makes real-time slow. Javascript can interact with a page without reloading it. Is it possible to load PHP pages on a page using Javascript? So that it would allow PHP to be loaded over and over without reloading.

I've seen it done with Chat rooms but not sure how it works.

Share Improve this question asked Jun 30, 2012 at 5:11 Tyler HughesTyler Hughes 6121 gold badge11 silver badges19 bronze badges 1
  • 1 Yes, ajax. And if you are doing ajax I would highly reend the jquery library as it makes it much easier – Kris Commented Jun 30, 2012 at 5:17
Add a ment  | 

3 Answers 3

Reset to default 3

We mostly use Ajax, which consists in a client-side Javascript code that calls a server-side page, with out leaving the page.

Here's an example that will get the displayed content of a page, using the GET method (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();

And here using the POST method (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);

Note that here we use the setRequestHeader method to change the headers of this HTTP request and, in this case, to change the Content-type and the Content-length (this header has a default value of 4096 bytes). Also, the setRequestHeader method must be called after the open method.

These links should help you:

https://developer.mozilla/en/Ajax

http://code.google./intl/pt-BR/edu/ajax/tutorials/ajax-tutorial.html

Yes it's incredibly mon. Read up on Ajax.

We call that AJAX!!! Just Read The documentation on internet about ajax

本文标签: PHP and Javascript working togetherStack Overflow