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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵