【问题标题】:Php API Returning whole object instead of Just messagePHP API 返回整个对象而不是消息
【发布时间】:2022-11-11 14:48:47
【问题描述】:

嘿,我使用 PHP 编写了一个用于插入数据的 rest api。我试图将消息呈现到我的 ajax 成功响应中,但我没有得到任何响应,而是一堆整个对象。

我的 php 返回码

if(mysqli_query($connection , $ins)){


    echo json_encode(array('message' => 'Item Added' , 'status' => true));

}else{

    echo json_encode(array('message' => 'Failed to add item' , 'status' => false));

}

这是我的ajax调用

 $.ajax({

            url : "http://localhost/cokeinventory/rest-api/api-insert-item.php",
            type : "POST",
            data : JSON.stringify({

                    item:itemname , unit:unit , date:expdate , bcode:bcode , blabel:blabel
            }),
            error:err=>{
                console.log(err)
            },
            success:function(data){
              console.log(data.message);
            }
        });   
    });

这就是我的回应

【问题讨论】:

  • if(mysqli_query($connection, $ins)){ echo json_encode(array('message' => 'Item added' , 'status' => true));出口(); }else{ echo json_encode(array('message' => '添加项目失败' , 'status' => false)); }
  • 这个问题与 HTML 有什么关系?
  • 你对这段代码有什么疑问?这是 PHP 问题,还是 jQuery 问题?请删除与您的问题无关的标签

标签: php html jquery ajax api


【解决方案1】:

回显后退出它正在显示这些字符串,因为它存在于 html 中

if(mysqli_query($connection , $ins)){
     echo json_encode(array('message' => 'Item Added' , 'status' => true));
     exit();
 }else{
   echo json_encode(array('message' => 'Failed to add item' , 'status' => false));
    exit();
 }

并使用 json 解码

$.ajax({

            url : "http://localhost/cokeinventory/rest-api/api-insert-item.php",
            type : "POST",
            data : JSON.stringify({

                    item:itemname , unit:unit , date:expdate , bcode:bcode , blabel:blabel
            }),
            error:err=>{
                console.log(err)
            },
            success:function(data){
             var obj = $.parseJSON(data);
              console.log(obj.message);
            }
        });   
    });

【讨论】:

  • 您不必回显响应并退出请求。这就是return 的含义
  • 为什么你强迫他返回 json 响应?他问了一个简单的问题,他需要成功回复的信息。
  • 因为那是你在编程中应该做的。遵循标准和原则,不要搞乱应用。这就是 OOP 的结构
  • @VüsalHüseynli 它没有用它仍然给我发送了一大堆对象
  • 它与php无关。这是jquery的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 2011-11-25
  • 2019-06-20
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
相关资源
最近更新 更多