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 运筹优化,gurobi,python
  • ¥20 画CAD几张图片内容如下1111111111111111111111111111111111111111111
  • ¥15 基于python的电影系统推荐
  • ¥20 springmvc重定向和返回json
  • ¥15 数学建模——参会安排怎么做
  • ¥15 电脑键盘实现触摸功能
  • ¥25 matlab无法将表达式转换为双数组怎么解决?
  • ¥15 单片机汇编语言相关程序
  • ¥20 家用射频美容仪技术规格
  • ¥15 大家帮我看看为什么错了