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 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘