简体   繁体   中英

How to get json Format from a sql-multi-query php-script to javascript?

I have a question for a project. I have a PHP-Script on a server like this:

    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$sql = "SELECT COUNT(*) as f FROM R;";
$sql.= "SELECT COUNT(*) as fo FROM Ro;";
$sql.= "SELECT P, U, D FROM Profile where U = 'lol';";
$sql.= "SELECT IU FROM I WHERE UID = '2';";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        echo json_encode($res->fetch_all(MYSQLI_ASSOC));

        $res->free();
    }
} while ($mysqli->more_results() && $mysqli->next_result());

I get a response like this:

    [{"f":"0"}][{"fo":"0"}][{"P":"0",U":"lol","D":"xD"}]
[{"I":"lol"},{"I":"lolol"}]

But when I request this reponse via javascript like:

$.post("http://localhost/lol/lol.php", {}, function(data){
console.log(data);
}, "json");

I receive null. But when I use the post.request without "json", I get a response but not in json format. How can I do this? Thank You very much for your help!!! Regards Felix

The answer was the following:

    $.post("http://localhost/lol.php", {}, function(data){
var pars1 = data.split('][').join(']-[');
var pars2 = pars1.split('\\n ').join('');
var pars3 = pars2.split('-');

  var f = JSON.parse(pars3[0]);
  var fo =  JSON.parse(pars3[1]);
  var po = JSON.parse(pars3[2]);
  var i = JSON.parse(pars3[3]);

Now you have 4 JSON Format Objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM