只有在有多个echo语句时才会打印Ajax post请求

时间:2015-10-07 21:37:31

标签: php ajax echo

我正在使用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确定

     

日期:星期四,2015年10月8日15:02:00 GMT

     

服务器:Apache

     

X-Powered-By:PHP / 5.6.11

     

Expires:Thu,1981年11月19日08:52:00 GMT

     

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

     

Pragma:no-cache

     

内容长度:20

     

Keep-Alive:超时= 5,最大= 190

     

连接:Keep-Alive

     

Content-Type:text / html;字符集= UTF-8

因此,基于内容长度,响应将被传回,但它以某种方式隐藏,以便javascript无法读取,并且在Chrome Web Developer中无法查看工具。如果我将回声线更改为:

echo $output.$output;

或者如果我添加第二个回声如下:

echo $output;
echo $output;

Content-Length更改为40,并打印以下内容:

  

{"响应":"错误"} {"响应":"错误"}

1 个答案:

答案 0 :(得分:0)

经过一些小编辑后,我设法让代码为我工作。我用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库,几乎可以简化任何事情。

这对我有用,我希望它可以帮到你!