大家好,这是不正常的:) !!

foo.php

     <?php
         if (isset($_POST['data']))
         $stringData = $_POST['data'];
         $file = "ciao.txt";
         $fh = fopen($file, 'w') or die("can't open file");
         fwrite($fh, $stringData);
         fclose($fh);

         ?>

file.js

    function WriteToFile() {
        var dataa = "foo bar";
     $.post("foo.php", {data: dataa}, function(result){ alert("ciaoooo!!");}
           , "json");
    }


这是错误,我无法在我的file.txt中写

注意:未定义的变量:stringData

我也尝试过这种功能

function WriteToFile() {
    var data = "foo bar";
$.ajax({
    url: 'foo.php',
    type: 'POST',
    data: { 'data' : 'data'},
    success: function() {
        alert('the data was successfully sent to the server');
    }
});

but the result is the same!! Anyone have some idea???

最佳答案

好的,我认为这是正在发生的事情:

您发布的代码(示例1中的foo.php / file.js)是正确的,并且可以正常工作。我不确定您是否要尝试直接在浏览器中访问foo.php URL。在这种情况下,什么都不会发布,因此$ stringData将是未定义的,并且会引发您看到的通知。

您需要做的是:
1.将file.js脚本包含在HTML文件中。
2.确保您已经包含了jQuery库
3.确保$ .POST中的PHP(foo.php)文件路径正确。
4.在HTML主体的onLoad函数上调用WriteToFile()

这是一个应该工作的HTML示例(如果需要,将路径更新为foo.php)

<script src ="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
function WriteToFile()
{
    var dataa = "foo bar";
    $.post("foo.php", {data: dataa}, function(result){ alert("ciaoooo!!");}, "json");
}
</script>

10-07 13:58
查看更多