【问题标题】:404 Not Found on Jquery AJAX JSON PHP POST在 Jquery AJAX JSON PHP POST 上找不到 404
【发布时间】:2015-03-26 16:13:38
【问题描述】:

我正在尝试将一些 JSON 数据发布到本地主机,但我不断收到 404 Not Found 错误,这很奇怪,因为 php 文件位于脚本中指定的正确位置。我将不胜感激任何有这方面经验的人的反馈。我收到这个错误是因为服务器由于某种未知原因找不到 ajax.php 文件吗?

<div class="container">
            <div class="header">
                <h3 class="text-muted">AJAX JSON Data</h3>
            </div>
            <div id="data-div">
                <form method="post" action="api/ajax.php" class="ajax">
                    <p><label for="firstname" class="contact-input-text">First Name</label> <br/>
                    <input id="first-name" name="firstname" type="text" maxlength="30" autofocus /></p><p><label for="lastName" class="contact-input-text">Last Name</label> <br/>
                    <input id="last-name" name="lastname" type="text" maxlength="30" autofocus /></p>
                    <p><input type="submit" id="submit-button" class="contact-input-text" value="submit" /></p>
                </form>
            </div>

        </div>

<script>
$('form.ajax').on('submit', function(){
            
            var jsondata = {};
            $(this).find('[name]').each(function(i, data){
                console.log(data);
                var that = $(this); 
                var key = that.attr('name');
                var value = that.val();
                jsondata[key] = value;
            });
            console.log(jsondata);

            $.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    dataType: 'json',
                    data: jsondata,
                    success: function(response){
                        console.log(response);
                    },
                    error: function(xhr){
                    console.log(xhr);
                    }
                });
            return false;

</script>

 

这里是 ajax.php 文件....

<?php 
	if(isset($_POST['submit'])) {
		$file = "data.json";
		$json_string = json_encode($_POST,JSON_PRETTY_PRINT);
		file_put_contents($file,$json_string,FILE_APPEND);
	}
?>

这是目录结构:

index.html (contains the form input fields and the ajax request)
ajax.php
/styles
/images

【问题讨论】:

  • 首先,在您进行 Ajax 请求时,您的表单中不需要 action="api/ajax.php"。其次,您的文件ajax.php 在哪里?在.,在./api/?
  • @D4V1D - 谢谢。 ajax.php 与脚本文件位于同一目录中。
  • 您可以使用文件所在文件夹的确切树形视图来编辑您的问题吗?
  • @Toshi 在脚本中指定的路径被应用为相对于文档/当前location。
  • ajax.php 是否与js 文件或html 文件位于同一目录中?

标签: javascript php jquery ajax json


【解决方案1】:

您是否确保 ajax 中的 url 正确?

也许不是这样:

url: 'ajax.php'

但是这个:

url: 'api/ajax.php'

【讨论】:

  • 如果您不打算实际回答该问题而是询问信息,请避免回答该问题。为此使用 cmets。
  • 由于他的函数.on('submit',中有return false,所以这些属性根本没有使用。
  • 可能是ajax代码中的url错误,从url:'ajax.php'变成url:'api/ajax.php'
  • @D4V1D,请支持我的声誉 :)
猜你喜欢
  • 2017-05-06
  • 2019-01-22
  • 2018-05-10
  • 1970-01-01
  • 2018-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多