【问题标题】:I keep getting this Fatal Error: Cannot use object of type stdClass as array我不断收到此致命错误:无法使用 stdClass 类型的对象作为数组
【发布时间】:2019-06-19 13:35:56
【问题描述】:

我一直在用这种简单的 javascript 和 php 通信将头撞到墙上。

我有一个要求用户输入两个数字的 HTML 表单。它应该将这两个数字作为 JSON 发送到服务器 (process.php)。在服务器中,它应该将两个数字相加并将结果发送回 JavaScript。之后,它将在 HTML 文件上打印结果。

javascript.js

$(document).ready(function(){
    $('#calcular').click (function(e){
        e.preventDefault();
        var numerosJSON = JSON.stringify($('#myForm').serializeArray());
        $.ajax({
            url: '/process.php',
            type:'post',
            data: numerosJSON,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            contentType: 'application/json',
            success: function(soma){
                                //shows result in a div in the html file
                $('#out').text(soma);
            }
        });
    });
})

process.php

$json = file_get_contents('php://input');
$numeros = json_decode($json, true);

$fst = $_POST['first'];
$snd = $_POST['second'];

$soma = $fst + $snd;

header('Content-Type: application/json, charset=utf-8');

echo json_encode($soma);

它确实发送了请求,但我总是收到错误:

致命错误:不能将 stdClass 类型的对象用作数组

你们能帮我解决这个问题吗?快把我逼疯了!

【问题讨论】:

    标签: php html json ajax


    【解决方案1】:

    在您发布的 PHP 代码中,您解码接收到的 JSON 对象但不使用它,而是尝试从 $_POST 检索值。解码对象后,每个序列化输入将拥有一个包含namevalue 子级的数组元素。如果您想按名称访问这些元素,则需要通过array_map() 或while/for 循环接收和解码的数组。为简单起见,我在示例中使用了按数组索引访问。

    <?php
    $json = file_get_contents('php://input');
    $numeros = json_decode($json, TRUE);
    
    $fst = $numeros[0]["value"];
    $snd = $numeros[1]["value"];
    $soma = $fst + $snd;
    
    header('Content-Type: application/json, charset=utf-8');
    echo json_encode($soma);
    

    【讨论】:

      猜你喜欢
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      • 2014-07-18
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多