【问题标题】:Ajax post is returning error function on callbackAjax 帖子在回调中返回错误函数
【发布时间】: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 会出现在那个参数中。哦,还有一个错误,比如说插入后验证,或者任何东西在插入后肯定会抛出错误

标签: php ajax


【解决方案1】:

有两个原因导致 status=0

  1. 在文件协议上运行
  2. Ajax 请求被导航事件取消

在你的情况下,我怀疑它是一个。所以它离开页面导航。在您的情况下,您单击的内容很可能是提交表单。由于您没有取消单击的默认操作,因此表单正在提交并杀死 Ajax 请求。所以停止发生默认操作。

$('#testimonial_add').click(function(event){
  event.preventDefault();
  ...
});

或者,如果您使用的是提交按钮,请将其更改为常规按钮,它将不再提交表单。

【讨论】:

  • 我可以在 URL 中提及函数名称,例如 working.php/函数名称
猜你喜欢
  • 1970-01-01
  • 2014-09-03
  • 2021-12-09
  • 2012-02-08
  • 2016-08-27
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多