将ajax变量写入txt文件

时间:2013-02-25 00:09:44

标签: php javascript ajax jquery

我有一个Facebook应用程序编码客户端,我想将令牌存储在我的服务器上供以后使用

有一个名为'token'的变量然后我创建了一个名为'apple'的新函数,将这个变量以json格式写入txt文件

$(document).ready(function(){

$("#submit").click(function(){

    //access token stuff
    var token = $("#link_input").val();
    //alert("Got Token: " + token + ". your application token");

    if (token.split('#access_token=')[1]) {
    var token = token.split('#access_token=')[1].split('&')[0];
    //alert(token);



function WriteToFile(apple)
    {
    $.post("save.php",{ 'token': apple },
        function(data){
            alert(data);
        }, "text"
    );
    return false;
    } 

我的php文件

<?php
$thefile = "new.json"; /* Our filename as defined earlier */
$towrite = $_POST["token"]; /* What we'll write to the file */
echo $towrite;
$openedfile = fopen($thefile, "w");
$encoded = json_encode($towrite);
fwrite($openedfile, $encoded);
fclose($openedfile);
return "<br> <br>".$towrite;

?>

但我不能写任何东西

2 个答案:

答案 0 :(得分:0)

您必须先在该位置创建该文件,然后设置正确的权限,否则PHP将无法编写该文件。

答案 1 :(得分:0)

现在,您在JS中定义了WriteToFile函数,但从不调用它。 将您的JS更改为:

$(document).ready(function(){

    $("#submit").click(function(){

        //access token stuff
        var token = $("#link_input").val();
        //alert("Got Token: " + token + ". your application token");

        if (token.split('#access_token=')[1]) {
            var token = token.split('#access_token=')[1].split('&')[0];
            WriteToFile(token);
        }
    }



    function WriteToFile(apple) {
        $.post("save.php",{ 'token': apple },
            function(data){
                alert(data);
            }, "text");
        return false;
    }

};

或者:

$(document).ready(function(){

    $("#submit").click(function(){

        //access token stuff
        var token = $("#link_input").val();
        //alert("Got Token: " + token + ". your application token");

        if (token.split('#access_token=')[1]) {
            var token = token.split('#access_token=')[1].split('&')[0];
            $.post("save.php",{ 'token': token }, function(data){
                    alert(data);
                }, "text");
        }
    }

};