2016-06-20 25 views
6

Voglio restituire dati json ma il mio codice non funziona. Non ricevo alcun messaggio di errore. Ho index.php, ajax.php e db.php. Db.php sta funzionando. Ma il mio codice Ajax non funziona. Dov'è il mio errore?Restituisci dati json con php

index.php:

<!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 
</head> 
<body> 
    <div id="test" style="width:500px;height:400px; margin:20px auto;"></div> 
<script> 
    $(window).load(function() { 
     $.ajax({ 
      dataType: "json", 
      url: 'ajax.php', 
      success:function(data){   
       $("#test").html(data); 
      } 
     }); 
    }); 
</script> 
</body> 
</html>  

ajax.php:

<?php 
require 'db.php'; 
$query="select lat,lng from locations order by id"; 
$result = pg_query($link, $query); 
if (!$result) { 
echo "An error occurred_xxx.\n"; 
}else { 
$arr = pg_fetch_all($result); 
echo json_encode($arr); 
} ?> 
+2

La vostra Console per gli sviluppatori spettacolo eventuali errori? Puoi mostrare l'output della richiesta AJAX nel pannello di rete? –

+0

Ho ora navigato in http: //localhost/php/index.php. –

risposta

6

Se vi aspettate JSON è necessario inviare a prescindere. Quello che stai facendo quando i tuoi errori di script, sta inviando text/html. Prova questo:

header("Content-Type: application/json"); 
require 'db.php'; 
$query="select lat,lng from locations order by id"; 
$result = pg_query($link, $query); 
$response = array(); 
if (!$result) { 
    $response = array(
     'status' => false, 
     'message' => 'An error occured...' 
    ); 
}else { 
    $response = array(
     'status' => true, 
     'message' => 'Success', 
     'data' => ph_fetch_all($result) 
    ); 
} 

echo json_encode($response); 

Ora, come si vedrà, inviamo JSON reale, impostando una corretta Content-Type intestazione e non mescolare testo e JSON in su.

Per gestire questa risposta all'interno del tuo jQuery, è sufficiente condizionare la risposta:

$(window).load(function() { 
    $.ajax({ 
     dataType: "json", 
     url: 'ajax.php', 
     success:function(data){   
      if(!data.status) { 
       $("#test").html("ERROR: " + data.message); 
      } else if(data.status) { 
       $("#test").html(data); 
      } 
     } 
    }); 
}); 
+0

grazie mille. –

+0

Ho provato questo esempio ho ottenuto json_decode() si aspetta che il parametro 1 sia stringa, matrice data in cosa significa? –

+0

@ FatihDoğan si scusa, avrebbe dovuto essere 'json_encode()'. – Darren