【问题标题】:Javascript/AJAX/PHP error: No element found and unable to write to a fileJavascript/AJAX/PHP 错误:未找到元素且无法写入文件
【发布时间】:2015-07-26 12:40:43
【问题描述】:

这几天我一直在努力解决这个错误。搜索了 stackoverflow 和其他网络资源,但到目前为止没有运气。

代码相当简单。我有一个调用 saveFile.php 的 test.html 文件。但是,我有两个问题。 1) 在 Firefox 中,我不断收到“未找到元素”错误。在 Chrome 中看不到这个问题。 2) 尽管 saveFile.php 似乎被调用了,但它并没有按应有的方式写入文件。两种浏览器都是这种情况,我真的需要能够写入文件。

这是 test.html 文件:

<!DOCTYPE html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>IIDS: Basic Boilerplate</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>

hello world

<script src="../components/jquery/jquery.js"></script>

<script type="text/javascript">

    $.ajax({
            type: "POST",
            url: "saveFile.php",
            //url: "http://localhost/~usesr1/mywork/saveFile.php",
            //dataType: "json",
            data: 'test',
            success:function(text) {
                    console.log(text);

            },
            error: function(xhr, status) {
                    alert("unable to save data");
            },

    });

</script>

</body>
</html>

这是saveFile.php:

<?php

    $tdata = "hello world this is a test";
    $testf = fopen('hello123', 'w+');
    fwrite($testf, $tdata);
    fclose($testf);

    echo "yes";
    // header("Content-Type: text/plain"); Got this from another stackoverflow question, but this didn't fix the problem.
    exit();

?>

这两个文件位于 ~/public_html 下的同一目录中。我给了目录 777 权限。这是一台运行 Ubuntu 14.04 的机器。

在 saveFile.php 中,尝试“GET”而不是“POST”,但再次失败。

我被困住了,任何帮助将不胜感激。谢谢。

编辑:此问题与 cmets 中链接的问题不重复。主要区别是我无法让我的 php 写入文件。只要 php 脚本能够写入文件,我不一定关心“找不到元素”错误。我只是决定在这篇文章中包含该错误,因为我认为它可能与我的实际问题有关。

【问题讨论】:

  • 你看过浏览器控制台中的请求/响应吗?
  • 如果您只是在浏览器中访问 saveFile.php 路由会发生什么?文件是否被创建?
  • 在您打开&lt;?php标签error_reporting(E_ALL); ini_set('display_errors', 1);后立即将错误报告添加到您的PHP文件顶部
  • 您是否搜索过“firefox no element found”?我找到了这个答案stackoverflow.com/a/976200/4137738,上面写着:使用header('Content-Type: text/plain');,Firefox 不会尝试将响应解析为 XML,并且应该没有错误。

标签: javascript php html ajax


【解决方案1】:

您必须指定 AJAX 事件何时发生。

由于您希望它在您打开页面时触发,请添加 $(document).ready 函数,它会在文档完成加载时触发。或者您可以将其绑定到例如按钮的.click() 事件。

<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
                type: "POST",
                url: "saveFile.php",
                data: 'test',
                success:function(text) {
                        console.log(text);   
                },
                error: function(xhr, status) {
                    alert("unable to save data");
                },
        });
    });
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 2010-11-01
    • 2014-06-07
    • 2015-05-03
    相关资源
    最近更新 更多