Ajax post请求只打印多个echo语句


Ajax post request only prints if there are more than one echo statement

我使用ajax来处理登录表单。请求内的一切都正常工作,只有一个异常。数据正在提交到文件login.php .

文件中的相关代码如下:

$dealer = $stmt->fetch(PDO::FETCH_ASSOC);
$a = [];
if (!$dealer) {
    $a['response'] = 'error';
} else {
    $a['response'] = 'ok';
}
$output = json_encode($a);
echo $output;
die();

当直接调用脚本时,会给出错误响应并回显给浏览器。但是,当通过post提交值时,什么也不会返回。如果我在die()调用之前的任何地方添加另一行,将一个字符回显到屏幕上,则所有内容都将像应有的那样回显,包括$output的值。

你知道为什么会出现这种情况吗?

编辑:

响应头如下:

HTTP/1.1 200 OK

日期:星期四,2015年10月8日15:02:00 GMT Apache服务器:

X-Powered-By: PHP/5.6.11

Expires: th, 19 Nov 1981 08:52:00 GMT

Cache-Control: no-store, no-cache, must-revalidate, post-check=0, precheck =0

杂注:no - cache

内容长度:20

Keep-Alive: timeout=5, max=190

连接:维生

的content - type: text/html;utf - 8字符集=

因此,基于Content-Length,响应被传递回来,但它以某种方式隐藏,使javascript无法读取它,并且它在Chrome Web开发人员工具中不可查看。如果我将回显行改为:

echo $output.$output;

或者添加第二个echo,如下所示:

echo $output;
echo $output;

Content-Length变为40,打印如下内容:

{"response"error"{"response"error"

我设法让你的代码为我工作后,一些小编辑。我用JQuery编写了一个请求来模仿来自客户端的AJAX请求。

PHP代码:

<?php
$dealer = true; // Imitating a successful login.
$a = array(); // '[]' wasn't working on my localhost setup.
if (!$dealer) {
    $a['response'] = 'error';
} else {
    $a['response'] = 'ok';
}
$output = json_encode($a);
header('Content-Type: application/json'); // THIS IS IMPORTANT! It tells Javascript that the body of the returned information is JSON.
echo $output;
exit(); // I prefer to only use die() if I'm echoing something when killing the script, it's just a matter of personal choice.

header('Content-Type: application/json');行确保PHP脚本返回的主体被客户端注册为JSON格式。

AJAX测试设置(HTML):

<p>Response: <span id="test">default</span></p>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
    var jqxhr = $.ajax("login.php").done(function(e) {
        document.getElementById("test").innerHTML = e.response;
    }).fail(function() {
        alert('Failed to fetch information.');
    });
</script>

我在这个答案中使用了jQuery,我建议你在你的应用程序中使用jQuery,因为它是一个了不起的Javascript库,几乎可以简化任何事情。

这对我有用,我希望它能帮助你!