【问题标题】:Can’t show my array value in json_encode php undefined [closed]无法在 json_encode php undefined 中显示我的数组值 [关闭]
【发布时间】:2021-09-15 10:46:09
【问题描述】:

这是我的 cart.php 文件。数组我编码为json并返回ajax函数:

 $data = array();

     $data['total'] = '10000';
     $data['quantity'] = '10';

 echo json_encode($data);

这是我的 index.php 文件。我创建函数 ajax 以在 cart.php 中返回我的数组值,但该值未定义:

 function view()
  {
    $.ajax({  
      url: 'cart.php',
      type:'POST',
      data:{action:'total'},
      datatype:'json',
      success: function (data) {
          
          alert(data.total);
       
      }
    });
  }

【问题讨论】:

  • 您显示的代码似乎不会产生您所描述的错误。正在发生其他事情,我们无法从这些信息中看到。

标签: javascript php arrays json ajax


【解决方案1】:

请将“datatype”改为“dataType”,否则系统无法得知dataType是JSON格式

    $.ajax({  
      url: 'cart.php',
      type:'POST',
      
      // the next line seems unnecessary
      //data:{action:'total'},
      
      dataType:'json',
      success: function (data) {
        
        /// data.total will now be 10000
        alert(data.total);

      }
    });

【讨论】:

  • datatype:'json' 确保 jQuery 到达成功回调之前解析 JSON。这在文档中有所描述。因此,OP的问题不在于缺乏解析。
  • @ADyson,仔细观察,问题的根源是单词 dataType 的拼写(这就是为什么当我之前添加 JSON.parse 时它起作用的原因)。注意:datatype:'json' 不起作用,dataType:'json' 起作用
  • 谢谢兄弟,但你错了数据类型大多数是数据类型而不是数据类型,但是当数据类型像这种数据类型时你的代码运行成功
  • 对不起,你是对的,自动解析必须是dataType
  • 无论如何谢谢你,但别忘了把它改成数据类型小写字母't'而不是数据类型'T'
【解决方案2】:
$.ajax({
   url: 'cart.php',
   type: 'POST',
   data:{action:'some action'},
   dataType:'JSON',
   cache:false,
   success:function(response){
        console.log(response)
   }
})

只返回来自 PHP 的数组。 Ajax 会自动发挥作用。

【讨论】:

    猜你喜欢
    • 2016-10-23
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    相关资源
    最近更新 更多