I am using a Jquery $.post
request to get a JSON response that is generated by PHP. When the request is complete, a success or error message is displayed. During development however, I sometimes have PHP errors which end up being returned instead of the JSON. When this happens, I just get the error message:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The code I have now looks like this:
var request = $.post(url, data, null, "json");
request.fail(on_failure);
var on_failure = function(jqXHR, text_status, error_thrown)
{
$("#text_status").empty().append(error_thrown);
};
I would like to be able to show the PHP error if one is returned rather than just indicate that there is a PHP error (just to speed up debugging). Obviously, if a non-JSON parsing error such as HTTP 404 occurs, I still want to display that. I found a method here的末尾,表示我可以使用类似的内容检测此错误
$.ajaxSetup({
error: function(jqXHR, exception) {
if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
}
}
});
但它似乎没有帮助我,因为它运行的每个请求而不是单个请求和(据我所知)它不允许访问返回数据中的错误消息。
答案 0 :(得分:1)
不确定您使用的是哪个版本的jquery。无论如何,您是否尝试删除json
dataType?
var request = $.post(url, data, null);
执行此jQuery将为您猜测dataType。
答案 1 :(得分:0)
我讨厌窃取mkross1983的功劳,但他没有回复我的请求,将他的评论转变为答案。 mkross1983说:
您是否尝试在“网络”标签下使用Firebug查看请求的结果?有时可以在那里看到错误,可以提供一些问题的线索
Firebug“Net”标签已被证明是一种有价值的调试工具。通过这种方式,我可以准确地看到发出了什么请求以及发送给它的响应。它甚至允许我查看随请求一起发送的标头和cookie。
谢谢你mkross1983