jQuery: ottenere una definizione da Wikipedia

jQuery: ottenere una definizione da Wikipedia

Ottenere una definizione da Wikipedia tramite jQuery richiede l'uso di uno script lato server che funga da proxy per la richiesta. Nel nostro esempio useremo uno script PHP la cui funzione principale è stata adattata a partire da quella proposta in questo articolo. Lo script restituirà un oggetto JSON che verrà poi utilizzato da jQuery all'atto del processamento di un form di ricerca. Vediamo i dettagli dell'implementazione.

Lo script PHP è il seguente:


header('Content-Type: application/json');

function getWikiDefinition($def)

// http://www.barattalo.it/2010/08/29/php-bot-to-get-wikipedia-definitions/
 
{
$url = 'http://it.wikipedia.org/w/api.php?action=opensearch&search='.urlencode($def).'&format=xml&limit=1';
  $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_HTTPGET, TRUE);

    curl_setopt($ch, CURLOPT_POST, FALSE);

    curl_setopt($ch, CURLOPT_HEADER, false);

    curl_setopt($ch, CURLOPT_NOBODY, FALSE);
    
    curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
    
    curl_setopt($ch, CURLOPT_REFERER, "");
    
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    
    curl_setopt($ch, CURLOPT_MAXREDIRS, 4);
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    
    curl_setopt($ch, CURLOPT_USERAGENT, 
    'Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.8) Gecko/20100722 Firefox/5.0.0');
    
    $page = curl_exec($ch);
    
    $xml = simplexml_load_string($page);
    
    if((string)$xml->Section->Item->Description) {
        return array('term' => (string)$xml->Section->Item->Text, 
                     'desc' => (string)$xml->Section->Item->Description, 
                     'url' => (string)$xml->Section->Item->Url);
    } else {
        return '';
    }
}


$definition = getWikiDefinition($_GET['d']);

echo json_encode($definition);

Lo script accetta il parametro GET d che contiene il termine da cercare e restituisce il seguente oggetto JSON:


{
  "term": "...",
  "desc": "...",
  "url": "..."
}

term è il termine cercato, desc è la sua descrizione e url è l'URL della pagina corrispondente di Wikipedia. jQuery elabora il form di ricerca in questo modo:


 $('#search').submit(function(event) {
  
    var $form = $(this);
    var term = $('#d', $form).val();
    
    $.ajax({
      type: 'GET',
      dataType: 'json',
      url: $form.attr('action'),
      data: 'd=' + term,
      success: function(data) {
      
        var html = '';
        html += '<div class="def">';
        html += '<h2>' + data.term + '</h2>';
        html += '<p>' + data.desc + '</p>';
        html += '<div><a href="' + data.url + '">' + data.url + '</a></div>';
        html += '</div>';
        
        $(html).appendTo($form);
        
      
      
      }
    });
    
  
    event.preventDefault();
  
});

L'oggetto data è l'oggetto JSON restituito dallo script PHP.

Torna su