An important component of AJAX technology is XMLHttpRequest. This object allows you to make HTTP requests to the server without the need to reload the page.
Usually, working with XMLHttpRequest is as follows:
1. Creating an instance of the XMLHttpRequest object
2. Setting an event handler that occurs when the state of an object changes (onreadystatechange)
3. Opening a connection (open) and sending a request (send)
Unfortunately, XMLHttpRequest only works with files that are in the same domain as the page using XMLHttpRequest. That is, a request can be made only to addresses with the same domain, protocol and port as the current page. This is done for security purposes and creates problems if you need to get data / content from another site.
')
Recently, this problem arose in front of me, a very simple solution was chosen, which will be discussed further.
Proxy! A simple and intuitive method for cross-domain queries. The essence of the method is as follows:
1. XMLHttpRequest accesses the PHP script on its domain, passing it the request method, address and parameters
2. PHP script, in turn, acts as a proxy. That is, it makes a request based on the parameters passed to it and returns the response of another JS server to the script
PHP script, which is a proxy for cross-domain query, is based on CURL.
This is actually the proxy.php script itself:
<?php
header("Content-Type: text/xml; charset=windows-1251");
//
$method = (empty($_GET['method'])) ? 1 : $_GET['method'];
$url = $_GET['url'];
$url = (empty($_GET['url'])) ? die("no url") : $_GET['url'];
$params = $_GET['params'];
//
$allowed = array(1 => "~http:\/\/(www\.)?habrahabr\.ru\/~", 2 => "~http:\/\/(www\.)?el\-egoisto\.com\/~");
$count = count($allowed);
for ($i = 1; $i <= $count; $i++)
{
if (preg_match($allowed[$i],$url))
{
// -
$ch = curl_init();
switch ($method)
{
case 1:
// GET
curl_setopt($ch, CURLOPT_URL, $url."?".$params);
break;
case 2:
// POST
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
break;
}
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
$header_size = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
$xml = substr($response,$header_size);
echo $xml;
curl_close($ch);
exit();
}
}
?>
XMLHttpRequest refers to it and sends 3 parameters:
1. method - 1 for GET request and 2 for POST
2. url - request address
3. params - request parameters
The PHP script checks for the presence of input parameters, checks whether it is allowed to send a request to the url (regexp array $ allowed) and actually sends the request and returns the response of the remote server.
From JS, this PHP script is used like this:
There are 2 functions for working with XMLHttpRequest - CreateReq and GetData. The first creates an instance of the object, and the second sets the handler and sends the request.
function CreateReq()
{
var req = null;
if (window.XMLHttpRequest)
{
try
{
req = new XMLHttpRequest();
}
catch(e)
{
req = null;
}
}
else if (window.ActiveXObject)
{
try
{
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
req = null;
}
}
}
return req;
}
function GetData(url,callback)
{
req = new CreateReq;
if(req != null)
{
req.onreadystatechange = callback;
req.open('GET', url, true);
req.send(null);
}
else alert(" ..");
}
Let's consider sending a GET request using the example of obtaining karma and strength from Habr :)
function GetHabraMe()
{
GetData("/proxy.php?method=1&url="+encodeURIComponent("http://habrahabr.ru/api/profile/lordeg"),GetHabraCallback);
}
function GetHabraCallback()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
var xmlDoc = req.responseXML;
var karma = xmlDoc.getElementsByTagName("karma").item(0).firstChild.data;
var rating = xmlDoc.getElementsByTagName("rating").item(0).firstChild.data;
var place = document.getElementById("data");
if(place != null)
{
place.innerHTML = ": "+karma+"<br>: "+rating+";
}
}
}
return false;
}
GetHabraMe will send a GET request to
habrahabr.ru/api/profile/lordeg using proxy.php and the result will “return” to the element with id “data”.
Sending a POST request is almost the same:
function GetPings()
{
var d_topic = document.getElementById("topic");
if (d_topic.innerHTML == " ")
{
GetData("/proxy.php?method=2&url="+encodeURIComponent("http://el-egoisto.com/frontend.php")+"¶ms="+encodeURIComponent("func=recent&owner=9&id=1&cutoff=48"),GetMyLastPingsCallback);
}
}
You can see the implementation in “combat conditions” here -
lord-phoenix.com (“current music” and “Habralordeg” links) :)
I do not pretend to originality, I just decided to issue a solution to the problem that arose before me in the form of a topic in a blog. Maybe someone will come in handy with my experience.
Materials on the topic:
1.
xmlhttprequest.ru2.
en.wikipedia.org/wiki/XMLHttpRequest3.
en.wikipedia.org/wiki/AJAX4.
ru.wikipedia.org/wiki/CURL