简体   繁体   English

如何调试 jquery AJAX 调用?

[英]How do I debug jquery AJAX calls?

I have been working on trying to get AJAX to work with Jquery.我一直在努力让 AJAX 与 Jquery 一起工作。 My big issue so far has been that I don't really know how to figure out where I'm making a mistake.到目前为止,我的大问题是我真的不知道如何找出我犯了错误的地方。 I don't really have a good way to debug AJAX calls.我真的没有调试 AJAX 调用的好方法。

I'm trying to set up an admin page where one of the functions I want to make is to change the permission set in my SQL database.我正在尝试设置一个管理页面,其中我想要创建的功能之一是更改 SQL 数据库中的权限集。 I know that the .click function is being triggered, so I've narrowed that down, but I'm not sure where in the chain from AJAX call to SQL query its going wrong.我知道 .click 函数正在被触发,所以我已经缩小了范围,但我不确定从 AJAX 调用到 SQL 查询的链中哪里出错了。

My .js code:我的 .js 代码:

$('#ChangePermission').click(function(){
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
        'user': document.GetElementById("user").value,
        'perm': document.GetElementById("perm").value
        }
    })
})

my .php handler:我的 .php 处理程序:

<?php  
require_once(functions.php);

echo $_POST["user"];

try{
    $DBH = mysql_start();

    $STH = $DBH->prepare("INSERT INTO people ( username, permissions ) values (?, ?)");

    $STH->bindParam(1, $_POST["user"]);
    $STH->bindParam(2, $_POST["perm"]);

    $STH->execute();
}
catch(PDOException $e){
    echo $e->getMessage;
}?>

Where the mysql_start is setup for the PDO function that I use successfully in my other SQL calls. mysql_start 是为我在其他 SQL 调用中成功使用的 PDO 函数设置的。

I have been researching and looking up tutorials for a few days now and I can't for the life of me figure out what's going wrong.我几天来一直在研究和查找教程,但我一生都无法弄清楚出了什么问题。 Are there tools I can use to figure out where the error is occuring?是否有工具可以用来找出错误发生的位置? I'm obviously interested in the answer to this specific issue, but I think my bigger issue here is that I have no idea where to start with debugging.我显然对这个特定问题的答案很感兴趣,但我认为我这里更大的问题是我不知道从哪里开始调试。 Thanks for your help!谢谢你的帮助!

Make your JQuery call more robust by adding success and error callbacks like this:通过添加这样的成功和错误回调,使您的 JQuery 调用更加健壮:

 $('#ChangePermission').click(function() {
     $.ajax({
         url: 'change_permission.php',
         type: 'POST',
         data: {
             'user': document.GetElementById("user").value,
             'perm': document.GetElementById("perm").value
         },
         success: function(result) { //we got the response
             alert('Successfully called');
         },
         error: function(jqxhr, status, exception) {
             alert('Exception:', exception);
         }
     })
 })

Using pretty much any modern browser you need to learn the Network tab.您几乎可以使用任何现代浏览器来学习“网络”选项卡。 See this SO post about How to debug AJAX calls .请参阅有关如何调试 AJAX 调用的SO 帖子。

You can use the "Network" tab in the browser (shift+ctrl+i) or Firebug .您可以使用浏览器中的“网络”选项卡 (shift+ctrl+i) 或Firebug
But an even better solution - in my opinion - is in addition to use an external program such as Fiddler to monitor/catch the traffic between browser and server.但在我看来,更好的解决方案是使用外部程序(例如Fiddler)来监视/捕获浏览器和服务器之间的流量。

if you are using mozilla firefox than just install an add-on called firebug .如果您使用的是 mozilla firefox,请不要只安装一个名为firebug的插件。

In your page press f12 in mozilla and firebug will open.在您的页面中,在 mozilla 中按 f12,firebug 将打开。

go for the net tab in firebug and in this tab go in the xhr tab.转到 firebug 中的net选项卡,然后在此选项卡中转到xhr选项卡。 and reload your page.并重新加载您的页面。 you will get 5 options in xhr Params Headers Response HTML and Cookies您将在xhr Params Headers Response HTML and Cookies获得 5 个选项

so by going in response and html you can see which response you are getting after your ajax call.因此,通过responsehtml您可以查看在 ajax 调用后得到的响应。

Please let me know if you have any issue.如果您有任何问题,请告诉我。

Firebug as Firefox (FF) extension is currently (as per 01/2017) the only way to debug direct javascript responses from AJAX calls. Firebug 作为 Firefox (FF) 扩展目前(根据​​ 01/2017)是调试来自 AJAX 调用的直接 javascript 响应的唯一方法。 Unfortunately, it's development is discontinued.不幸的是,它的开发已停止。 And since Firefox 50, the Firebug also cannot be installed anymore due to compatability issues :-( They kind of emulated FF developer tools UI to recall Firebug UI in some way.从 Firefox 50 开始,由于兼容性问题,Firebug 也无法再安装 :-( 他们模拟了 FF 开发人员工具 UI 以某种方式调用 Firebug UI。

Unfortunatelly, FF native developer tools are not able to debug javascript returned directly by AJAX calls.不幸的是,FF 本机开发人员工具无法调试由 AJAX 调用直接返回的 javascript。 Same applies to Chrome devel.同样适用于 Chrome 开发。 tools.工具。

I must have disabled upgrades of FF due to this issue, since I badly need to debug JS from XHR calls on current project.由于这个问题,我必须禁用 FF 的升级,因为我非常需要从当前项目的 XHR 调用中调试 JS。 So not good news here - let's hope the feature to debug direct JS responses will be incorporated into FF/Chrome developer tools soon.所以这里不是好消息 - 让我们希望调试直接 JS 响应的功能很快就会被整合到 FF/Chrome 开发者工具中。

2020 answer with Chrome dev tools 2020 年 Chrome 开发工具的答案

To debug any XHR request :要调试任何 XHR 请求

  1. Open Chrome DEV tools (F12)打开 Chrome 开发工具 (F12)
  2. Right-click your Ajax url in the console在控制台中右键单击您的 Ajax url

Chrome 控制台 Ajax 请求

for a GET request :对于GET 请求

  • click Open in new tab单击在新选项卡中打开

for a POST request :对于POST 请求

  1. click Reveal in Network panel单击“网络”面板中的“显示”

  2. In the Network panel :网络面板中

    1. click on your request点击您的请求

    2. click on the response tab to see the details单击响应选项卡以查看详细信息Chrome 网络面板的响应标签

you can use success function, once see this jquery.ajax settings你可以使用成功功能,一旦看到这个jquery.ajax 设置

 $('#ChangePermission').click(function(){
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
        'user': document.GetElementById("user").value,
        'perm': document.GetElementById("perm").value
        }
       success:function(result)//we got the response
       {
        //you can try to write alert(result) to see what is the response,this result variable will contains what you prints in the php page
       }
    })
})

we can also have error() function我们也可以有 error() 函数

hope this helps you希望这对你有帮助

Install Firebig to see where your error is happening.安装 Firebig 以查看错误发生的位置。 You could also set up a callback in your ajax call to return your error messages from your PHP.您还可以在 ajax 调用中设置回调以从 PHP 返回错误消息。 Eg.例如。

error: function(e){
     alert(e);
     }

Just add this after jQuery loads and before your code.只需在 jQuery 加载之后和代码之前添加它。

$(window).ajaxComplete(function () {console.log('Ajax Complete'); });
$(window).ajaxError(function (data, textStatus, jqXHR) {console.log('Ajax Error');
    console.log('data: ' + data);
    console.log('textStatus: ' + textStatus);
        console.log('jqXHR: ' + jqXHR); });
$(window).ajaxSend(function () {console.log('Ajax Send'); });
$(window).ajaxStart(function () {console.log('Ajax Start'); });
$(window).ajaxStop(function () {console.log('Ajax Stop'); });
$(window).ajaxSuccess(function () {console.log('Ajax Success'); });

here is what I would do in order to debug and get the php errors into javascript console.log after an ajax call:这是我为了在ajax调用后调试并将php错误输入javascript console.log而要做的事情:

    $('#ChangePermission').click(function () {
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
            'user': document.GetElementById("user").value,
            'perm': document.GetElementById("perm").value
        },
        success: function (data) {
            console.log(data);  
        },
        error: function (data) {
            console.log(data);
        }
    });
});

on the php side I would start by asking for all error returned to string concat and echo as a json encoded response that will includes php error messages as well if any.在 php 方面,我首先要求将所有错误返回到字符串 concat 并作为 json 编码的响应回显,其中还包括 php 错误消息(如果有)。

<?php

error_reporting(E_ALL);
require_once(functions . php);
$result = "true";
$DBH = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH->prepare("INSERT INTO people ( username, permissions ) values (?, ?)");

if (isset($_POST["user"]) && isset($_POST["perm"])) {
    $STH->bindParam(1, $_POST["user"], PDO::PARAM_STR);
    $STH->bindParam(2, $_POST["perm"], PDO::PARAM_STR);
}
try {
    $STH->execute();
} catch (PDOException $e) {
    $result .= $e->getMessage;
}
echo json_encode($result);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM