dongsui0929 2019-02-17 21:11
浏览 65

使用PHP从数组创建JSON并使用javascript解码它

if i am decoding a array with php i get JSON with brackets:

$data = array();
$data[0]["id"] = 23;
$data[0]["modul"] = "my modul";

echo '' .json_encode($data). '';

i'm getting a JSON like this:

[{"id":23,"modul":"my modul"}]

when i want this to decode with javascript there is nothing to decode cause javascript wants JSON without brackets

var myObj = JSON.parse(mySendJSONData);

i already tried to use this before parsing:

myObj = myObj[0];

but it did't solve it.

more clearly: i want to use server side events to send JSON to the client:

SERVER:

<?php
header( 'Content-Type: text/event-stream' );
header( 'Cache-Control: no-cache' );

    $data = array();
    $data[0]["id"] = 23;
    $data[0]["modul"] = "my modul";

    echo 'data: ' .json_encode($data). "

";
flush();
?>

CLIENT:

  var source = new EventSource("myServerSideEvent.php");

    source.onmessage = (event) => {
        var myObj = JSON.parse(event.data);     
        document.getElementById("moduldialog").innerHTML = myObj.modul;
    } 
  • 写回答

1条回答 默认 最新

  • douchun5969 2019-02-17 22:15
    关注

    You're sending JSON-encoded data, which should be a string. But you're not delineating it as a string in the output. Try:

    echo 'data: \'' .json_encode($data). "'
    
    ";
    
    评论

报告相同问题?