How to display error returned by $.ajax call?
我有一个永远需要加载的代码,最后当我放置错误处理程序时,它会显示警告,但我需要知道它返回了什么错误?我怎么知道?
编辑:找不到请求的URL,但我确定该URL:是主机上的有效URL,可能有什么问题?我甚至可以在浏览器中直接访问它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | // process logging in a user from sidebar $("#login-form").submit(function(event) { $('input:submit').attr("disabled", true); $("p.form-result").empty(); $('p.form-submit').after('<p class="loading"><img src="<?php bloginfo('template_directory'); ?>/img/loading.gif" alt="" /> </p>'); $.ajax({ url: '<?php bloginfo('template_directory'); ?>/ajax/login.php', type: 'POST', data: $(this).serialize(), dataType: 'json', success: function(data){ $('.loading').remove(); $('input:submit').attr("disabled", false); if (data.status) { // success $("p.form-result").html('<span class="success">' + data.message + '</span>'); window.setTimeout(function(){location.reload()},3000); } else { // error $("p.form-result").html('<span class="error">' + data.message + '</span>'); } }, error: function(data){ alert('error'); } }); return false; }); |
jquery函数
1 2 3 | error : function(jqXHR, textStatus, errorThrown){ } |
这是此事件的jquery文档:
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are"timeout","error","abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as"Not Found" or"Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn. Note: This handler
is not called for cross-domain script and JSONP requests. This is an
Ajax Event.
我们可以知道参数
当Ajax调用中包含一些无效参数时,将执行Ajax调用中的错误事件。下面的函数将通过抛出错误并在警报中显示错误定义来帮助您理解错误代码。
1 2 3 | error: function(xhr, ajaxOptions, thrownError){ alert(xhr.status); }, |
使用错误函数的数据参数来警告错误及其属性。它模仿你的实际错误。
1 2 3 | error: function(data){ alert(data); } |
根据此问题(http://stackoverflow.com/questions/95600/jquery-error-option-in-ajax-utility)答案,数据(错误)对象的可能值
1 2 3 4 | timeout - when your specified timeout is exceeded error - http error, like 404 notmodified - when requested resource was not modified since last request parsererror - when an xml/json response is bad |
改变这个
1 | url: '<?php bloginfo('template_directory'); ?>/ajax/login.php', |
以此
1 | url: '<?php bloginfo("template_directory"); ?>/ajax/login.php', |
:)
尝试在字符串和变量之间添加"+"(如果进行了concatate)。这样地:
1 | url: '<?php bloginfo('+template_directory+'); ?>/ajax/login.php' |