Ajax:JSON数据的第1行第1列的意外字符

时间:2018-03-01 13:51:34

标签: php jquery ajax

我是AJAX的新手。我查看过以前的帖子,看到这是一个常见的问题。通常的答案是数据实际上不是JSON格式。在我的情况下肯定是这样 - 正确的响应之前是来自早期回声输出的其他数据,如下所示:

<button type="button" id="dotest" name="dotest" >SAVE</button>{"foo":"bar"} 

这是创建此输出的测试代码:

HTML

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="../js/jquery-3.3.1.min.js"></script>
</head>
<body>
<?php include "../php/bin/test-bin.php"; ?>
<script src="../js/test.js"></script>
</body>
</html>

JS

$('#dotest').click(function(){testCode()});
function testCode()
{
    $.ajax({
      type: 'POST',
      dataType: 'json',
      data: {testvar:true},
      url:'../php/bin/test-bin.php',
      success: function(formdata) {
       alert(formdata['foo']);
      },
      error: function(xhr, status, error) {
        alert(xhr.responseText);
      },
    });
}

PHP

<?php
echo '<button type="button" id="dotest" name="dotest" >SAVE</button>';
if(filter_has_var(INPUT_POST, 'testvar'))
{
  $myArr = array("foo" => "bar");
  $json = json_encode($myArr);
  return;
}

如果我将echo按钮语句移到PHP代码的末尾,那么不需要的文本就不会出现在响应中。

我的代码中有错误吗?或者有没有办法在echo调用后刷新PHP输出?我试过了flush(),但它没有用。

你能给予的任何帮助都会对我的血压有益!

修改

我已经完成了建议并将Ajax调用放在一个单独的文件中。我遇到了同样的问题。在测试中我删除了几乎所有的代码,留下了这个(需求和定义在这一点上什么都不做):

<?php

// include global constants etc
require_once(__DIR__.'/../inc/config.php');
require_once(__DIR__.'/../inc/errorhandler.php');
require_once(__DIR__.'/../inc/common.php');

// fl_data
@define('FL_PREVVAL', 0);
@define('FL_CURRVAL', 1);

$data = array('animal' => 'horse', 'vehicle' => 'cart');
$json = json_encode($data);
echo $json;

Ajax响应是一个错误,但xhr.responseText包含格式正确的JSON。

如果删除两个define语句,则响应成功并使用相同的数据。放回echo之前的任何代码会产生相同的错误情况。

我做错了什么!

0 个答案:

没有答案