【发布时间】:2018-08-01 11:05:48
【问题描述】:
我正在使用 ajax 将数据发布到名为 working.php 的页面,数据存储在数据库中意味着一切正常,但在回调时抛出错误函数。
这是脚本:
<script>
$(document).ready(function(){
$('#testimonial_add').click(function(){
var nm=$('#name').val();
var message=$('#msg').val();
$.ajax({
type:'post',
url:'working.php',
data:{name:nm, msg:message},
success: function(html){
alert(html);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
</script>
Working.php 页面
<?php
include('../function.php');
$name = $_POST['name'];
$message = $_POST['msg'];
if($name == null || $message == null){
echo 'All fields are required';
}
else{
$query = "INSERT INTO testimonials(testimonial_name,testimonial_text) VALUES ('".$name."','".$message."')";
dml($query);
echo 'Data has been inserted';
}
?>
在错误功能中警告 textstatus 是错误 并且 errorThorwn 是空警报框
我也可以在 ajax 的 url 中给出 php 函数名称
这里是被调用的 Dml 函数
function dml($query){
$db=mysqli_connect('localhost','root','','entrepreneurshipdp')
or die('not connected');
mysqli_query($db,$query);
mysqli_close($db);
}
【问题讨论】:
-
你能有 alert();在错误中:函数获取 textStatus 参数?
-
另外,我不知道PHP文件中的dml()是什么,但是你完全确定它在运行查询后不会抛出错误吗?
-
textStatus 参数在警报中显示错误。我认为在我的数据库中获取记录时不会引发错误
-
不要让框架猜测您的数据类型,明确设置它们,这样就不容易出错。如果您希望响应为 html,则在 jquery 中使用
dataType: 'html'在 php 中使用header('Content-type: text/html')。 -
好的,那么请告诉我响应的状态码,我希望像这样的 sg 会出现在那个参数中。哦,还有一个错误,比如说插入后验证,或者任何东西在插入后肯定会抛出错误