2013-06-01 18 views
5

Sto provando a usare jQuery $ .ajax() ma sto affrontando alcune difficoltà.

Ecco il campo di testo che voglio usare per POST:

<input name="url" class="url" type="text" > 

Ecco il codice:

$.ajax({ 
     type: "post", 
     url: "file.php", 
     data: $(this).serialize(), 
     success: function(data) { ............... 

Ora questa è la file.php:

<?php 
if($_REQUEST['url']) 
{ 

    $url = $_REQUEST['url']; 
    $url = file_get_contents($url); 
    // I would need now to return something here but not sure how??!! 
} 
?> 

Ora , la mia domanda è, come restituire le variabili in questo codice PHP e usarle nel mio codice qui sopra, voglio dire nella parte positiva di $ .ajax(). Inoltre, se voglio eseguire alcuni elementi aggiuntivi nella variabile $ url, come farlo? Come restituirli? :/

risposta

1

È sufficiente stampare/echo il valore di 'ritorno'.

file.php

<?php 
if($_REQUEST['url']) 
{ 

    $url = $_REQUEST['url']; 
    $url = file_get_contents($url); 
    // I would need now to return something here but not sure how??!! 
    echo "something"; 
} 
?> 

Poi, nel tuo JS:

$.ajax({ 
    type: "post", 
    url: "file.php", 
    data: $(this).serialize(), 
    success: function(data) { 
     console.log(data); // "something" 
    } 
}); 

Come nota a margine. Sembra che il tuo script accetti qualsiasi URL e lo recuperi. È possibile abusare di script del genere. Assicurati di esserne consapevole.

+0

Ed è corretto usare cose del genere: "$ ('qualche casella di testo ') .writeText (data); "? –

2

Se si desidera restituire alcune variabili/campi, il modo migliore sarebbe quello di echo una stringa JSON. Ecco un piccolo esempio:

codice PHP:

<?php 
if($_REQUEST['url']) 
{ 

    $url = $_REQUEST['url']; 
    $url = file_get_contents($url); 

    $result['var1'] = 'something'; 
    $result['var2'] = 500; 

    echo json_encode($result); 
} 
?> 

codice JS:

$.ajax({ 
    type: "post", 
    url: "file.php", 
    data: $(this).serialize(), 
    dataType: 'json', // maybe not needed? I do not know if jQuery autodetects it 
    success: function(data) { 
     // here you can use data.var1 and data.var2 to read the fields 
    } 
});