繁体   English   中英

如何从PHP数组返回JSON字符串

[英]How to return json string from php array

我正在做我不明白的事情。 在OOP中编写了php代码,从中获取的值是对象。 但是我想将此OOP对象转换为JSON数据,以供javascript使用。 所以我将转换后的对象转换为php端的数组。 尝试在脚本上使用json_encode函数只是保持返回错误。 因此,我尝试使用范围外的函数,它起作用了,但是js继续拒绝数据。 下面是JS文件

 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(); 

它将返回此错误“ SyntaxError:JSON.parse:JSON数据的第1行第129行的字符串文字中的错误控制字符”,而没有JSON.parse,它将返回data.username控制台日志的未定义。 以下是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; } 

请帮助我解决这个错误,谢谢您。

只需使用json函数json_encodejson_decode将数组转换为json字符串,反之亦然:

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

您需要设置响应头,并确保您没有违反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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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