weixin_33743661 2016-05-11 15:57 采纳率: 0%
浏览 95

使用ajax写入文件

I've never really used AJAX before so I'm trying to get familiar. I have an html page:

<html>
<script type="text/javascript" src="jquery-1.12.3.min.js"></script>

<script>
    function write(){
        $.ajax({
        type: 'POST',
        url: "write.php",
        data: "something",
        success: function(result) {
            alert('the data was successfully sent to the server');
        }
        })
    }
</script>

Click to write some stuff
<a href="javascript:write()" class="write">Write</a>
</html>

And the associated write.php file in the same directory:

<?php
error_reporting(E_ALL);
$data = $_POST['data'];
$f = fopen('file.txt', 'w+');
fwrite($f, $data);
fclose($f);
?>

When I click the link, I get the success message, but the file is not created on the server. Not really sure what to investigate. Have confirmed I have write access to the directory

  • 写回答

1条回答 默认 最新

  • lrony* 2016-05-11 16:14
    关注

    Look, if you're going to use jQuery use it all of the way. First, your link shouldn't have any inline JavaScript.

    <a href="#" class="write">Write</a>
    

    When clicked you capture the click of your link event in your main jQuery code by its class (and stop the default behavior of the click):

    <script>
        $(document).on('click', '.write', function(event) {
            event.preventDefault();
    

    You're not sending what you think your are sending to the PHP script as the $_POST array expects key / value pairs. Create a key/value pair(s) for your data:

            $.ajax({
            type: 'POST',
            url: "write.php",
            data: {something: 'foo'}, // key value pair created, 'something' is the key, 'foo' is the value
    

    Don't use alert() for troubleshooting., use console.log() instead.

                success: function(result) {
                    console.log('the data was successfully sent to the server');
                }
            });
        });
    </script>
    

    Now, when you send the data you'll have something in $_POST['something']:

    <?php
        error_reporting(E_ALL);
        $data = $_POST['something']; // the key we sent was "something"
        $f = fopen('file.txt', 'w+');
        fwrite($f, $data);
        fclose($f);
    ?>
    

    Now the text file should contain "foo" because you have actually sent something to the PHP script which can be parsed. The only other thing you need to do is to make sure the PHP script has permissions to open and write to a file on your server.

    评论

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图