当ajax方法返回错误时如何打印输出?

时间:2013-12-16 10:12:58

标签: javascript php jquery ajax

我有像这样的$ .ajax方法

<form class="hidden code-box" method="GET" name="sample">
<div dir="ltr"><textarea class="php" name="codeguru"></textarea></div>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="submit" value="Run" />
<img class="hidden" style="vertical-align: middle;" alt="Try PHP  " src="http://code.guru99.com/img/ajax-loader.gif" name="ajax-loader" title="Try PHP " />
<div class="hidden stdout"></div>
<div class="hidden stderr"></div>
</form>

$.ajax({
            type: 'GET',
            url: '/exec.php',
            dataType: 'JSONP',
            data: {code : code},
            success: function(data) 
            {
                //alert(data.result);
                var data = data.result;
                $(loader).addClass('hidden');
                var stdout = $(form).children('.stdout');
                if (data.search("Parse error")>0)
                {
                    var str = data.replace('<b>Parse error</b>:  ','');
                    $(stdout).html(str);
                    $(stdout).removeClass('hidden');    
                }   
                else
                {
                    $(stdout).html(data);
                    $(stdout).removeClass('hidden');
                }   
            },
            jsonpCallback: 'mycallback',
            error: function (xhr, ajaxOptions, thrownError,err,textStatus) {
                var stdout = $(form).children('.stdout');
                alert (stdout);
                $stdout.html("Fatal error generated!!! Please check your code");
                $stdout.removeclass('hidden');
            }
        });

现在我想打印因$ .ajax方法而生成的错误。我试过这个。

error: function (xhr, ajaxOptions, thrownError,err,textStatus) {
                    var stdout = $(form).children('.stdout');
                    alert (stdout);
                    $stdout.html("Fatal error generated!!! Please check your code");
                    $stdout.removeclass('hidden');
                }

请帮忙

2 个答案:

答案 0 :(得分:3)

试试这个:

$( document ).ajaxError(function( event, request, settings ) {
console.log(settings.url);
});

or

$.ajax({
            type: 'GET',
            url: '/exec.php',
            dataType: 'JSONP',
            data: {code : code},
            success: function(data) 
            {
            },
            error: function(ts) { console.log(ts.responseText) }
});

答案 1 :(得分:0)

你在stdout中不需要$,因为它已经是一个jquery对象..

试试这个

 error: function (xhr, ajaxOptions, thrownError,err,textStatus) {
            var stdout = $(form).children('.stdout'); //here stdout is jquery object
            alert (stdout);
            stdout.html("Fatal error generated!!! Please check your code"); 
       //--^---notice missing $ here
            stdout.removeClass('hidden');
            //-----------^----- here notice uppercase `C`
 }