2017-06-07 2 views
0

Ich bin neu auf HTTP-Anfrage und PHP. Ich habe einen http:Abrufen von Daten von einer Variablen durch HTTP-Anfrage

xmlhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
     var doc = xmlhttp.response; 
     myFunc(doc); 
     } 
    }; 
    xmlhttp.open("GET",some.php",true); 
    xmlhttp.responseType = "document"; 
    xmlhttp.send(null); 

Die PHP-Datei:

<!DOCTYPE html> 
    <html> 
     <head> 
     <meta charset="utf-8"> 
     <title></title> 
     </head> 
     <body id="idk"> 
     <?php 
     include("include1.inc"); 
     include_once("include2.inc"); 

     $cxn = mysqli_connect($host,$user,$passwd,$dbname) or die("Could not connect to the server at this time."); 
     $table = 'table'; 

     $data = retrieveData($table, $cxn);//selects data from mysql db return array 
     var_dump($data); 

     ?> 
     </body> 
    </html> 

Wie würde ich die Datenvariable erhalten, die meine Array aus meiner Datenbank hält? Wenn ich die Variable dump oder drucke, wird das Array an `responseText übergeben. Gibt es einen eloquenteren Weg, dieses Array zu erfassen?

+1

Schriftfarbe bedeutet, dass Sie Zitate vergessen haben. – C2486

+0

'xmlhttp.open (" GET ", some.php", wahr); '=>' xmlhttp.open ("GET", "some.php", wahr); ' – Enstage

Antwort

0

Sie legen den Antworttyp als "Dokument" fest, sodass Sie HTMLDocument onbject als Antwort erhalten. Also, wenn Sie nur Datenvariable erhalten müssen versuchen, Ihren Code auf diese Weise ändern: javascript:

xmlhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
     var doc = xmlhttp.response; 
     myFunc(doc); 
     } 
    }; 
    xmlhttp.open("GET","some.php",true); 
    xmlhttp.responseType = "json"; 
    xmlhttp.send(); 

und PHP:

<?php 
     include("include1.inc"); 
     include_once("include2.inc"); 

     $cxn = mysqli_connect($host,$user,$passwd,$dbname) or die("Could not connect to the server at this time."); 
     $table = 'table'; 

     $data = retrieveData($table, $cxn);//selects data from mysql db return array 
     echo json_encode($data); 
?> 

Bitte beachten Sie, dass in diesem Fall PHP-Skript enthält keine HTML-Tag, nur PHP-Code.

+0

Dies funktionierte perfekt @ user1722564. Dies konvertiert meine $ Daten Variable in ein Json-Objekt, um es mir zu ermöglichen, es zu manipulieren und die Informationen aus ihm herauszuholen. – user3533795