简体   繁体   中英

echo json_encoded($array) passes previous echo

I don't know jQuery so I'm sorry if this is a stupid question.

When i passes value from php to javascript even previous message printed with echo are passed, how could I avoid this?

php

  $Connection = new Connection("...");
  $array = $Connection->arrCol("SELECT IT FROM global", "IT");
  echo json_encode($array);

jQuery

$(document).ready(function(){
$("button").click(function(){
    $.get("services/test.php", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});
 });

result

CONNECTED at (localhost) (user: root) (db: ...) stausUptime: 440790 Threads: 1 Questions: 1244 Slow queries: 0 Opens: 53 Flush tables: 1 Open tables: 1 Queries per second avg: 0.2 (message "echoed" by method of Connection in php)

["..."] (requested data)

If your Connection class does an echo and you don't want that mixed into your JSON output, you will have to control the output buffer.

For example:

// Start catching the output
ob_start();

// Run code that echoes unwanted stuff under the hood
$Connection = new Connection("...");
$array = $Connection->arrCol("SELECT IT FROM global", "IT");

// Clear the output buffer and stop buffering (i.e. discard that echo)
ob_end_clean();

// Output JSON
header('Content-Type: application/json');
echo json_encode($array);

You should take a look at output buffering in php.

Call the ob_start(); function at the beginning of your php code, and before your last echo statement call ob_end_clean(); to clean the output buffer from the previous echo/print statements.

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