为什么 return 会添加换行符?
我通过 ajax 调用 saveVideo.php ,而 $result 总是在顶部有两个换行符,我不知道它们来自哪里。它应该只是 addVideo 中的 $id 变量。新视频上传后,我需要在 ajax 中使用 id。
即使使用trim(),开发人员工具中 saveVideo ajax 调用的输出前面也有 2 个换行符。
以下是所有相关代码:
saveVideo.php:
<?php
require_once '../model.php';
$m = new Model;
$video = new Video;
$user = requireLogin();
$video->file = $_POST['url'];
$video->lib = 0; //sets library to be personal.
$video->title = mysql_escape_string($_POST['video-title']);
$video->desc = mysql_escape_string($_POST['video-description']);
$video->userId = $user->id;
$result = $m->addVideo($video);
echo trim($result);
?>
addVideo 函数:
function addVideo($video, $lib = 1) {
// Adds video to database and associates it with a user id
$qstring = "mysqlquery";
$result = mysql_query($qstring);
$id = mysql_insert_id();
if (!$result) {
die("Error adding video to database.");
}
return $id;
}
I'm calling saveVideo.php via ajax and $result always has two linebreaks at the top, I don't see where they could be coming from. It should be simply the $id variable in addVideo. I need the id to ajax in the new video once it's uploaded.
Even with trim(), the output from the saveVideo ajax call in Developer tools has 2 linebreaks in front of it.
Here's all the relevant code:
saveVideo.php:
<?php
require_once '../model.php';
$m = new Model;
$video = new Video;
$user = requireLogin();
$video->file = $_POST['url'];
$video->lib = 0; //sets library to be personal.
$video->title = mysql_escape_string($_POST['video-title']);
$video->desc = mysql_escape_string($_POST['video-description']);
$video->userId = $user->id;
$result = $m->addVideo($video);
echo trim($result);
?>
the addVideo function:
function addVideo($video, $lib = 1) {
// Adds video to database and associates it with a user id
$qstring = "mysqlquery";
$result = mysql_query($qstring);
$id = mysql_insert_id();
if (!$result) {
die("Error adding video to database.");
}
return $id;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在开始
之前或结束
?>
标记之后查找不必要的空行。如果块之外有空行,它们将被视为页面内容的一部分,并作为 PHP 响应的一部分发送。
这也适用于
../model.php
。那里的空行也会做同样的事情。另外,当你调试类似的东西时,如果你使用
var_dump
而不是echo
,你会省去很多麻烦。这会产生类似的输出
,告诉您
$result
不是神秘换行符的来源。Look for unnecessary blank lines before your opening
<?php
or after your closing?>
tags. If there are blank lines outside of a<?php ?>
block they will be treated as part of the page content and be sent as part of the PHP response.This applies to
../model.php
as well. Blank lines in there will do the same thing.Also, when you're debugging something like this you'll save a lot of hair pulling if you use
var_dump
rather thanecho
.This would produce output like
which would tell you that
$result
is not the source of the mysterious line breaks.您可以使用正则表达式甚至 str_replace 来删除这些换行符。
You can use a regexp or even a str_replace to remove those line breaks.