简体   繁体   中英

How to return json string from php array

I am doing something i don't understand how. written a php code in OOP and the value gotten from it are objects. but i want to convert this OOP object to JSON data to be used in by javascript. so I converted my converted my objects to array on the php end. the try to use the json_encode function on it the script just keep returning errors. so i tried using a function i scope out, it worked but the js keeps on rejecting the data. Below is the JS file

 var ajax = new XMLHttpRequest(); ajax.open('GET','user.php',true); ajax.setRequestHeader("Content-type","application/json"); ajax.onreadystatechange = function(){ if(ajax.readyState == 4 && ajax.status ==200){ var data = JSON.parse(ajax.responseText.trim()); console.log(data); console.log(data[username]); } } ajax.send(); 

it will return this error "SyntaxError: JSON.parse: bad control character in string literal at line 1 column 129 of the JSON data" without the JSON.parse it return undefind fro the data.username console log. Below is the PHP SCRIPT

  //header("Content-type: application/json"); require_once 'core/init.php'; function array2json($arr) { /*if (function_exists('json_encode')) { echo "string"; return json_encode($arr); }*/ $pars = array(); $is_list = false; $keys = array_keys($arr); $max_length = count($arr) - 1; if (($keys[0] == 0) and($keys[$max_length] == $max_length)) { $is_list = true; for ($i = 0; $i < count($keys); $i++) { if ($i != $keys[$i]) { $is_list = false; break; } } } foreach($arr as $key => $value) { if (is_array($value)) { if ($is_list) $parts[] = array2json($value); else $part[] = '"'.$key. ':'.array2json($value); } else { $str = ''; if (!$is_list) $str = '"'.$key. '"'. ':'; if (is_numeric($value)) $str. = $value; elseif($value === false) $str. = 'false'; elseif($value === true) $str. = 'true'; else $str. = '"'.addslashes($value). '"'; $parts[] = $str; } } $json = implode(',', $parts); if ($is_list) return '['.$json. ']'; return '{'.$json. '}'; } $user = new User(); $json = array(); if (!$user - > is_LOggedIn()) { echo "false"; } else { foreach($user - > data() as $key => $value) { $json[$key] = $value; //$json =json_encode($json,JSON_FORCE_OBJECT); //echo $json; } /*$details = '{"'.implode('", "', array_keys($json)).'"'; $data = '"'.implode('" "', $json).'"}'; die($details.' / '.$data);*/ $json = array2json($json); print $json; } 

PLEASE HELP ME OUT TO SORT THIS ERROR THANK YOU.

Just use the json functions json_encode and json_decode to convert arrays into json string or vice versa:

$myArray = array("value1", "value2");
echo json_encode($myArray);

You need to set the response headers, and ensure you are not violating CORS:

    /*
     * Construct Data Structure
     */
    $response =
    [
        'value1',
        'value2'
    ];

    /*
     * Format Data
     */
    $jsonResponse = json_encode ( $response, JSON_PRETTY_PRINT );

    /*
     * Prepare Response
     */
    header('content-type: application/json; charset=UTF-8');

    /*
     * ONLY if you want/need any domain to be able to access it.
     */
    header('Access-Control-Allow-Origin: *');

    /*
     * Send Response
     */
    print_r ( $jsonResponse );

    /*
     * Return with intended destruction
     */
    die;

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