【问题标题】:how to access an array within a json php to javascript/jquery如何访问 json php 中的数组到 javascript/jquery
【发布时间】:2018-03-28 10:37:50
【问题描述】:

我在php中有这个功能

$everything= array($ary);
$response = (json_encode(array('code'=>'0','id'=>$id,'usr'=>$usr, 'everything'=>$everything)));

如何使用 javascript/jquery 访问它。我现在有这个。

javascript

 websocket.onmessage = function(ev) {
   received = JSON.parse(ev.data);
   var everything = received.everything;
 };

我能够获取除变量$everything 之外的所有数据,我如何从php 传递它并在javascript 中检索它。

【问题讨论】:

  • 我无法重现该问题。
  • 好的,我可以给你完整的代码,但不能亲自在这里或其他地方,如果你不与其他人分享,我将不胜感激?
  • 没有。产生问题的代码需要在问题内,否则问题无用。创建一个Minimal, Complete, and Verifiable example
  • 这是问题所在的代码

标签: javascript php jquery websocket


【解决方案1】:

试试这个:

$response = json_encode(array('code'=>'0','id'=>$id,'usr'=>$usr, 'everything'=>$ary));

它将非常适合您。

【讨论】:

  • 我将如何从 javascript/jquery 调用它?请提供完整答案
  • 作为。你告诉过一切都运作良好,而不是一切都很有价值。我对 websocket 了解不多。
【解决方案2】:

您需要使用索引 ex。收到[0]

websocket.onmessage = function(ev) {
  received = JSON.parse(ev.data); 
  var everything = received[0].everything; 
  document.write(everything);            
};

【讨论】:

  • 永远不要使用document.write
  • 仅用于检查响应
  • 然后使用console.log()
  • doesnt work for some reason 说 uncaught can not read property everything but I have defined it in php
  • received 是对象而不是数组。
【解决方案3】:

一个更好的方法是在 php 中使用 implode 函数 将数组转换为字符串,然后传递它

$everything= array($ary);
 ConvertEverything = implode(' ',$everything);
$response = (json_encode(array('code'=>'0','id'=>$id,'usr'=>$usr, 'everything'=>$ConvertEverything )));

JavaScript

 websocket.onmessage = function(ev) {
   received = JSON.parse(ev.data);
   var everything = received.everything;
 };

【讨论】:

    【解决方案4】:
    <?php
    header('Content-Type: application/json');
    $everything= array($ary);
    $response = (json_encode(array('code'=>'0','id'=>$id,'usr'=>$usr, 'everything'=>$everything)));
    ?>
    <script>
    websocket.onmessage = function(ev) {
    var code = ev.data;
    var id= ev.id;
    var usr = ev.usr;
    
            };
    
    </script>
    

    【讨论】:

    • 请不要只是将代码转储到答案中。请记住,我们是来教育人们的,所以请花时间解释问题是什么以及您的回答如何帮助解决问题。
    • 除此之外,由于响应没有 data 属性,您的逻辑被破坏了。
    • 已经试过了,它可以获取单个变量的数据,但是如何为everything获取它,因为`everything`都是一个数组
    • 打印($response);
    • 这毫无意义。您不能在 WebSocket 消息中发送标头。
    猜你喜欢
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2023-02-04
    相关资源
    最近更新 更多