Come chiamare le funzioni PHP con jQuery

December 22

La libreria jQuery offre la possibilità di emettere in modo asincrono una richiesta HTTP POST, ad esempio per chiamare una funzione PHP in un file esterno. Per chiamare una funzione PHP utilizzando jQuery, è necessario creare la funzione PHP da sola, senza una definizione di funzione, in un file esterno che è possibile fare riferimento tramite un URL. Utilizzare il metodo di jQuery "post" per richiamare la funzione.

istruzione

1 Creare un nuovo file PHP utilizzando un editor o il blocco note. Creare una funzione PHP da solo senza una definizione di funzione circostante. Ad esempio, per creare una funzione PHP che si apre un file e imposta un flag, tipo:

<? Php

$ Fh = fopen ( "flag.dat") || die ( "Impossibile aprire il file!");

fwrite ($ fh, "flag");

fclose ($ FH);

?>

2 Utilizzare un editor o il Blocco note per creare un documento HTML per il codice JavaScript per chiamare la funzione PHP. Ad esempio, digitare:

<! DOCTYPE HTML PUBLIC "- // W3C // DTD XHTML 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<Html xmlns = "http://www.w3.org/1999/xhtml">

<Head>

<Meta http-equiv = "Content-Type" content = "text / html; charset = utf-8" />

<Title> Chiama PHP </ title>

</ Head>

<Body>

</ Body>

</ Html>

3 Includere la libreria jQuery tra i tag <head> del documento HTML. Ad esempio, digitare:

<Metodo script type "text / jsvascript" per chiamare la funzione PHP nel file esterno. Ad esempio, digitare:

<Script type = "text / javascript">

$ (Document) .ready (function () {

$.post("http://example.com/phpfunction.php");

});

</ Script>