Report syntax errors in a JSON object with jQuery and / or Javascript

What is the best way to report a syntax error when I load a JSON feed using jQuery? I can set the error message settings as follows:

error: function(xhr){
    alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}

however, this function does not work when the URL I named loads a valid page (although it is not associated with a JSON object). Moreover, I can’t check the data that it returns, because (at least according to Firebug) it jQuery.getJSONbreaks with a syntax error before passing the object to the function that executes it.

The reason I want to report errors is because this is my way of checking if the user has provided a URL that will issue the correct JSON feed.

Here's a related answer that requires control over what the server will respond . Here is the syntax error that Firebug gives me. The syntax error of Firebug gives me http://img.skitch.com/20090623-8c97g47jha4mn6adqqtjd41cwy.jpg

Any ideas? Thanks

+3
source share
4 answers

Thanks to all who responded. Since I called the JSON channel from an external domain, I was unable to simply use the jQuery AJAX functions and pull out the feed as "text" instead of "json". jQuery allows you to pull "json" and "script" from a remote source.

PHP script, , . jQuery AJAX, , URL-, "". , , JSON, . jQuery JSON ; $.getJSON , URL.

+1

ajaxerror

$(document).ajaxError(function(event, request, ajaxOptions, thrownError){
  if ( 4==request.readyState) { // failed after data has received
    alert(ajaxOptions['url'] + " did not return valid json data");
  }
  else {
    alert("something else wnet wrong");
  }
});
$.ajax() $.getJSON()
function foo() {
  // $.getJSON("http://localhost/test.txt", function(data){});
  $.ajax({
    type: "GET",
    url: "http://localhost/test.txt",
    success: function (data, textStatus) {
      alert("succuess");
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert("request failed: " + textStatus);
    },
    dataType: "json"
  });
}

edit: , ajax (dataType: "json" ) getJSON() ( .ajax(dataType: "json" ), data = window["eval"]("(" + data + ")")... , , t () script. , firebug , html- json-.
dataType: "string" jsson parser lib.

+3

URL- XHR , IDE IDE, JavaScript. , - .

, , , .

0

When adding a Diodeus answer, insert your potentially offensive JSON into this tool: http://jsonformatter.curiousconcept.com/

If you have firebug, you can even hack into the way the site is used in software, although this can be disapproving.

0
source

Source: https://habr.com/ru/post/1711045/


All Articles