【问题标题】:Ajax request json PHP - jsondata mixed with other prints (echoes)Ajax 请求 json PHP - jsondata 与其他打印混合(回声)
【发布时间】:2021-03-04 12:47:25
【问题描述】:

我有一个从 php 检索 jsondata 的 ajax 脚本 - 到目前为止还可以,但是由于其他输出(回声)与 jsonstring 一起出现,因此无法解析数据。我搜索了这个问题,似乎应该在将相关输出(json)从 php 发送回客户端(ajax)时添加标题信息。当我这样做时,没有任何东西被退回。我该如何解决这个问题?

这是客户端检索 json 的样子(连同其他打印)

connected to database { jsondata comes here .. } success

那么,如何隔离回传的jsondata呢?

客户端(ajax),sn-p

    $(function(){
            $.ajax({
                type:'POST',
                url: 'endpoint.php?function=getJson',
                data: {name: 'Stockholm'},
                success: function (data){
                console.log('success',data);
                
                var jsonData = JSON.parse(data); //error here when parsing!!!

 

服务器端(php),sn-p

//header('Content-Type: application/json'); //if I add thos row no data is sent back
$result =  $_GET['function']($_POST['name']);
echo $result;


function getJson($name) {

  ...
  return $json;
}

【问题讨论】:

  • 警告$_GET['function']($_POST['name']) 似乎不是很安全...
  • 您在浏览器的网络面板中看到了什么? (打开面板,执行请求,检查“原始输出”)。
  • @Syscall - 感谢您的警告,我稍后会调查。现在只想让它工作,使用环回
  • @Syscall - 就我所见,它看起来不错,甚至通过wireshark检查了http。 jsondata就在那里!但与其他印刷品混在一起
  • "mixed with other prints":你应该避免它们:输出必须只包含 JSON。

标签: php json ajax


【解决方案1】:

我通过清理标准输出(输出缓冲区)解决了这个问题,将函数调用放在 echo $result 之前的一行

即:

$result =  $_GET['function']($_POST['name']);   
ob_clean(); // this call solved the problem
echo $result;

来源:

https://www.php.net/manual/en/function.ob-clean.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    相关资源
    最近更新 更多