dongshi3061 2015-05-20 10:41
浏览 188
已采纳

在AJAX响应中追踪换行符

I'm doing an AJAX request and somehow a trailing newline is added somewhere.
My PHP script echoes (or is supposed to echo) 'SUCCESS' if the request succeeded, 'ERROR' otherwise.
But currently it returns: 'SUCCESS' (i.e. 'SUCCESS ').
I saw that by adding an alert("!" + msg + "!") that showed the line break.

My AJAX call:

function addMedia() {
    var addMediaName = $("#addMediaName").val();
    var notif;
    if(addMediaName != ""){
        $.ajax({
            url : '../../controler/add/addMedia.php',
            type : 'POST',
            data : "mediaName="+ addMediaName,
            dataType : 'text',
            success: function(msg,data, settings){
                if(msg == 'SUCCESS'){
                    $.toaster({ priority : 'success', title : 'Success', message : 'Mode created' });
                } else {
                    $.toaster({ priority : 'warning', title : 'Failed', message : 'Mode already exists' });
                }
            },
        });
    }
}

My PHP controller:

<?php
include ('../../model/request/add.php');
if((include_once '../../model/request/add.php')===FALSE) exit('erreur include');
$mediaName = $_POST['mediaName'];
$mediaName = ucfirst(strtolower($mediaName));
$media = addMedia($mediaName);
?>

And the addMedia function:

function addMedia($mediaName)
{
    global $conn;
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    try {
        $sql = 'INSERT INTO media (mediaName) VALUES 
        ("'.$mediaName.'")';
        $conn->exec($sql);
        echo 'SUCCESS';
    } catch(PDOException $e) {
        echo 'ERREUR';
    }
}

Any idea where that newline is coming from and how I can fix it?

  • 写回答

2条回答 默认 最新

  • douyun3887 2015-05-20 10:59
    关注

    That is most likely caused by the end of the PHP file, where a newline follows the ?>.

    Now while it is possible to die/exit at a previous point, I consider it a much cleaner solution to simply remove the ?>.
    The closing tag is not required by PHP, and it is usually even considered better practise not to use it, see this SO question.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题