【发布时间】: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