【问题标题】:$.ajax call not working and not display error message$.ajax 调用不起作用且不显示错误消息
【发布时间】:2019-03-02 04:38:14
【问题描述】:

我的简单脚本需要您的帮助。我希望当用户单击图像(带有 id="menu_en")以在 php 页面中执行外部脚本(在我的情况下为 english.php),但 ajax 调用不起作用。甚至使用“error:”语句“alert(xhr.status);”对我没有帮助,因为警报只显示“0”并隐藏在第二个......我错在哪里? 这是我放置在页面正文中的代码:

 <script src='jquery-1.11.3.min.js'></script>       
    <script>
        $(document).ready(function(){                       
            $('#menu_en').on('click',function(){                    
                var enID = '1';
                var url = 'index.php';                          

                $.ajax({
                    type:'POST',
                    dataType: 'JSON',
                    url:'english.php',                                  
                    data: {language_id: enID},
                    success:function(data){
                        alert('Success!');
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status);
                    }

                });             
            });
        });
    </script>

【问题讨论】:

  • error 例程的第二个参数实际上是 textStatus 如果您在 error 例程中使用 alert(textStatus) 会发生什么?
  • 您是否检查过开发人员工具中的响应?响应可能不是 JSON。
  • 告诉我们english.php 做了什么
  • Have you inspected the response in your developer tools 我想添加大多数浏览器允许您按 f12,然后您可以查看 AJAX 调用发生的实际网络请求。这将为您提供更多信息等。在 Mozilla 中,您按 f12 转到网络面板并确保在左侧选择了 XHR。然后显然触发呼叫并查看会发生什么(单击呼叫并检查左侧的内容,例如“响应”)等...
  • file "english.php" 只是设置一些会话值

标签: php jquery ajax


【解决方案1】:

你可能没有从english.php返回回复

$result = array(
  'msg' => true
);
echo json_encode($result);

在 javascript 代码中也使用 complete

<script>
    $(document).ready(function(){                       
        $('#menu_en').on('click',function(){                    
            var enID = '1';
            var url = 'index.php';                          

            $.ajax({
                type:'POST',
                dataType: 'JSON',
                url:'english.php',                                  
                data: {language_id: enID},
                success:function(data){
                    alert('Success!');
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                },
                complete: function (result) {
                    console.log(result);
                }

            });             
        });
    });
</script>

完成各种结果..

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2014-01-28
    • 2021-04-23
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多