简体   繁体   English

Ajax保存功能到服务器无法正常工作

[英]Ajax save function to server doesn't work correctly

I'm working on a website that let's users simply save a note, to be accessed later. 我正在一个网站上工作,使用户可以简单地保存便笺,以便以后使用。 I'm however having quite some trouble with actually saving the note. 但是我在保存笔记时遇到了很多麻烦。 I first had it set to automatically save on each keypress, but it's better if I have the user press on a button to save the file. 我首先将其设置为在每次按键时自动保存,但是最好让用户按下按钮来保存文件。 What you'll also see in the code is that the note gets saved as the users IP address, when the user then visits the site again he'll see the same note (if he has the same IP again). 您还将在代码中看到的是,该注释被保存为用户的IP地址,当用户再次访问该站点时,他将看到相同的注释(如果他再次具有相同的IP)。

The error I get now when clicking the save button is: 单击保存按钮时出现的错误是:

PHP Warning:  file_put_contents() [<a href='function.file-put-contents'>function.file-put-contents</a>]: Filename cannot be empty in /home/martmart/public_html/index.php on line 41

My index.php: 我的index.php:

<?php

$note_name = 'note.txt';
$uniqueNotePerIP = true;

if($uniqueNotePerIP){

// Use the user's IP as the name of the note.
// This is useful when you have many people
// using the app simultaneously.

if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$note_name = 'notes/'.$_SERVER['HTTP_X_FORWARDED_FOR'].'.txt';
}
else{
$note_name = 'notes/'.$_SERVER['REMOTE_ADDR'].'.txt';
}
}


if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
// This is an AJAX request

if(isset($_POST['note'])){
// Write the file to disk
file_put_contents($note_name, $_POST['note']);
echo '{"saved":1}';
}

exit;
}

$note_content = 'Write something here :D';

if(file_exists($note_name) ){
$note_content = htmlspecialchars( file_get_contents($note_name) );
}

function saveNow() {
// Write the file to disk
file_put_contents($note_name, $_GET['note']);
echo '{"saved":1}';
}

?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Marty Testweb</title>
<!-- Our stylesheet -->
<link rel="stylesheet" href="assets/css/styles.css" />
<!-- A custom google handwriting font -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Courgette" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="assets/audiojs/audio.min.js"></script>
<script>
audiojs.events.ready(function() {
var as = audiojs.createAll();
});
</script>
</head>

<body>

<div id="pad">
<h2>Note</h2>
<textarea id="note"><?php echo $note_content ?></textarea>
</div>

<!-- Initialise scripts. -->

<script>
function saveNow()
{
alert("<?php saveNow(); ?>");
}
</script>


<button id="save" onclick="saveNow()">Save Note</button>

<!-- JavaScript includes. -->

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="assets/js/script.js"></script>
</body>

<div id="footer">
<footer>
<a href="">
<div id="footer_right">
Version 0.1.2
</div id="footer_right">
</a>
<audio src="assets/audiojs/music.mp3" preload="auto"></audio>
<div id="footer_left">
Save function not working yet
</div id="footer_left">
</footer>
</div id="footer">
</html>

The script.js: script.js:

$(function(){

var note = $('#note');

var saveTimer,
lineHeight = parseInt(note.css('line-height')),
minHeight = parseInt(note.css('min-height')),
lastHeight = minHeight,
newHeight = 0,
newLines = 0;

var countLinesRegex = new RegExp('\n','g');

// The input event is triggered on key press-es,
// cut/paste and even on undo/redo.

note.on('input',function(e){

// Count the number of new lines
newLines = note.val().match(countLinesRegex);

if(!newLines){
newLines = [];
}

// Increase the height of the note (if needed)
newHeight = Math.max((newLines.length + 1)*lineHeight, minHeight);

// This will increase/decrease the height only once per change
if(newHeight != lastHeight){
note.height(newHeight);
lastHeight = newHeight;
}
}).trigger('input');    // This line will resize the note on page load

function ajaxSaveNote(){

// Trigger an AJAX POST request to save the note
$.post('index.php', { 'note' : note.val() });
}
});

I don't really know how to solve this, so any help is greatly appreciated. 我真的不知道如何解决这个问题,因此非常感谢您的帮助。 I just want to have the file save with the same name as the user's IP address, when he click on the button. 我只想在用户单击按钮时使用与用户IP地址相同的名称保存文件。 Please keep in mind I'm still a big newbie with these more advanced features so please point out anything I did wrong (but also please explain it easy :) ). 请记住,我仍然是这些功能更高级的新手,因此请指出我做错的任何事情(但也请简单地说明一下:))。

Thanks for reading, 谢谢阅读,

Mart. 市场。

First of all I would suggest considering whether having the filename be the IP address is a good idea...many workplaces and other group settings share the same IP address, so any user at a workplace like that would see the note left by any other user at the same workplace. 首先,我建议考虑是否将文件名作为IP地址是一个好主意...许多工作场所和其他组设置共享相同的IP地址,因此像这样的工作场所中的任何用户都会看到其他人留下的注释用户在同一工作场所。

As to your error, I think the problem may be that you didn't declare $note_name as a global variable within your function. 至于您的错误,我认为问题可能在于您没有在函数$note_name声明为全局变量。 Try changing it to this: 尝试将其更改为此:

function saveNow() {
    global $note_name;
    // Write the file to disk
    file_put_contents($note_name, $_GET['note']);
    echo '{"saved":1}';
}

In PHP if you want to use a global variable (one that wasn't declared inside a function or class) within a function, you always have to use the global keyword as shown above. 在PHP中,如果要在函数内使用全局变量(未在函数或类内部声明的变量),则必须始终使用global关键字,如上所示。 Using global variables can be avoided entirely if you structure your code a bit differently, but that's another topic. 如果代码的结构有所不同,可以完全避免使用全局变量,但这是另一个主题。

I wonder why you didn't get a notice about it not being defined though...while you're still developing you might want to put this at the top of your code: 我不知道为什么您没有收到关于未定义的通知...在继续开发时,您可能希望将其放在代码的顶部:

error_reporting(E_ALL);

PS Although your code will work without doing this, for security reasons it would be good to specify the JSON MIME type before outputting JSON from PHP, eg: PS虽然您的代码无需这样做即可工作,但是出于安全原因,最好在从PHP输出JSON之前指定JSON MIME类型,例如:

function saveNow() {
    global $note_name;
    // Write the file to disk
    file_put_contents($note_name, $_GET['note']);
    header('Content-type: application/json');
    echo '{"saved":1}';
    exit;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM