Ошибка ajax запроса parsererror

Been getting a «parsererror» from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.

My project is in MVC3 and I’m using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.

Dropdown: (this loads the «Views» from the list in the Viewbag and firing the event works fine)

@{
    var viewHtmls = new Dictionary<string, object>();
    viewHtmls.Add("data-bind", "value: ViewID");
    viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)

Javascript:

this.LoadViewContentNames = function () {
    $.ajax({
        url: '/Admin/Ajax/GetViewContentNames',
        type: 'POST',
        dataType: 'json',
        data: { viewID: $("#view").val() },
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            debugger;
            alert("Error");
        }
    });
};

The above code successfully calls the MVC method and returns:

[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
 {"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]

But jquery fires the error event for the $.ajax() method saying «parsererror».

Получил «parsererror» из jquery для запроса Ajax, я попытался изменить POST на GET, возвращая данные несколькими способами (создание классов и т.д.), но я не могу понять, что проблема есть.

Мой проект находится в MVC3, и я использую jQuery 1.5
У меня есть раскрывающийся список и в событии onchange я запускаю вызов, чтобы получить некоторые данные на основе того, что было выбрано.

Dropdown: (загружает «Views» из списка в Viewbag и срабатывает событие отлично)

@{
    var viewHtmls = new Dictionary<string, object>();
    viewHtmls.Add("data-bind", "value: ViewID");
    viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)

JavaScript:

this.LoadViewContentNames = function () {
    $.ajax({
        url: '/Admin/Ajax/GetViewContentNames',
        type: 'POST',
        dataType: 'json',
        data: { viewID: $("#view").val() },
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            debugger;
            alert("Error");
        }
    });
};

Вышеупомянутый код успешно вызывает метод MVC и возвращает:

[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
 {"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]

Но jquery вызывает событие ошибки для метода $.ajax(), говорящего «parsererror».

When making an AJAX request using jQuery, it is common to encounter the «parsererror» response. This error message occurs when the server returns a response that is not valid JSON. There are several reasons why this error may occur, including incorrect content type, incorrect JSON syntax, and other issues with the server-side code. Fortunately, there are several methods that can be used to resolve this error and ensure that your AJAX requests are successful.

Method 1: Check the Content Type

If you are facing the issue of jQuery returning «parsererror» for ajax request, you can try fixing it by checking the Content Type of the response. Here’s how you can do it:

Step 1: Set the Content Type of the response to «application/json» in the backend code. This can be done in PHP using the following code:

header('Content-Type: application/json');

Step 2: In your jQuery ajax request, set the «dataType» property to «json». This will tell jQuery to expect a JSON response.

$.ajax({
    url: 'your_url_here',
    dataType: 'json',
    success: function(response) {
        // Handle the response here
    },
    error: function(xhr, status, error) {
        // Handle the error here
    }
});

Step 3: In the success callback function, check the Content Type of the response using the «getResponseHeader» method of the xhr object.

success: function(response, status, xhr) {
    var contentType = xhr.getResponseHeader("Content-Type");
    if (contentType.indexOf("application/json") !== -1) {
        // Handle the JSON response here
    } else {
        // Handle other types of response here
    }
}

That’s it! By checking the Content Type of the response, you can ensure that jQuery correctly parses the JSON response and you no longer get the «parsererror» issue.

Method 2: Validate the JSON Response

To fix the «parsererror» issue with jQuery AJAX request, you can validate the JSON response. Here’s how you can do it step by step:

  1. First, make sure that the server is sending a valid JSON response. You can use a JSON validator tool to check the response.

  2. In your jQuery AJAX request, set the «dataType» property to «json». This will tell jQuery to parse the response as JSON.

$.ajax({
    url: 'your-url',
    dataType: 'json',
    success: function(response) {
        // Handle the response
    },
    error: function(xhr, status, error) {
        // Handle the error
    }
});
  1. In the «success» callback function, check if the response is valid JSON using the «JSON.parse()» method. If the response is not valid JSON, handle the error.
success: function(response) {
    try {
        var json = JSON.parse(response);
        // Handle the JSON response
    } catch (e) {
        // Handle the parse error
    }
},
  1. If the response is valid JSON, you can access the data using the «json» variable.
success: function(response) {
    try {
        var json = JSON.parse(response);
        var data = json.data;
        // Handle the data
    } catch (e) {
        // Handle the parse error
    }
},
  1. In the «error» callback function, check the status code and handle the error accordingly.
error: function(xhr, status, error) {
    if (xhr.status === 400) {
        // Handle the bad request error
    } else if (xhr.status === 401) {
        // Handle the unauthorized error
    } else {
        // Handle other errors
    }
}

That’s it! By validating the JSON response, you can fix the «parsererror» issue with jQuery AJAX request.

Method 3: Inspect Server-side Code

To fix the «parsererror» issue in jQuery Ajax request, you can inspect the server-side code to debug the issue. Here are the steps to do it:

  1. Check the response headers: The first step is to check the response headers to ensure that the server is sending the correct content type. You can use the getResponseHeader() method to check the value of the «Content-Type» header.
$.ajax({
    url: 'your-url',
    type: 'GET',
    success: function (data, textStatus, xhr) {
        var contentType = xhr.getResponseHeader('Content-Type');
        console.log(contentType);
    }
});
  1. Check the response data: If the content type is correct, then you can check the response data to see if it is valid JSON. You can use the JSON.parse() method to parse the response data and check for any errors.
$.ajax({
    url: 'your-url',
    type: 'GET',
    success: function (data, textStatus, xhr) {
        var contentType = xhr.getResponseHeader('Content-Type');
        if (contentType.indexOf('application/json') !== -1) {
            try {
                var jsonData = JSON.parse(data);
            } catch (e) {
                console.log(e);
            }
        }
    }
});
  1. Check the server-side code: If the response data is valid JSON, then the issue may be with the server-side code. You can check the server-side code to ensure that it is properly formatting the JSON response. For example, if you are using PHP, you can use the json_encode() method to encode the data as JSON.
$data = array('name' => 'John', 'age' => 30);
header('Content-Type: application/json');
echo json_encode($data);

By following these steps, you can inspect the server-side code to debug the «parsererror» issue in jQuery Ajax request.

Method 4: Use a JSON Parser

To fix the «parsererror» issue in jQuery ajax requests, you can use a JSON parser to parse the response data. Here’s how you can do it:

  1. First, make sure that the response data is in a valid JSON format. You can use a tool like JSONLint (https://jsonlint.com/) to validate the JSON data.

  2. In your jQuery ajax request, set the «dataType» option to «text» instead of «json». This will prevent jQuery from automatically parsing the response data as JSON.

$.ajax({
  url: "your-api-endpoint",
  dataType: "text",
  success: function(response) {
    // Parse the response data as JSON using a JSON parser
    var data = JSON.parse(response);
    // Do something with the parsed data
  },
  error: function(jqXHR, textStatus, errorThrown) {
    console.log(textStatus, errorThrown);
  }
});
  1. In the «success» callback function, use the JSON.parse() method to parse the response data as JSON. This will convert the JSON string into a JavaScript object that you can work with.

  2. Handle any errors that may occur during the parsing process by wrapping the JSON.parse() method in a try-catch block.

$.ajax({
  url: "your-api-endpoint",
  dataType: "text",
  success: function(response) {
    try {
      // Parse the response data as JSON using a JSON parser
      var data = JSON.parse(response);
      // Do something with the parsed data
    } catch (e) {
      console.log("Error parsing JSON data:", e);
    }
  },
  error: function(jqXHR, textStatus, errorThrown) {
    console.log(textStatus, errorThrown);
  }
});

By using a JSON parser to parse the response data, you can avoid the «parsererror» issue that may occur when jQuery tries to automatically parse the data as JSON.

Method 5: Consider Other Issues with the Server

If you are getting a «parsererror» response from jQuery ajax request, it means that the server is returning a malformed JSON response. This error can occur due to various reasons such as incorrect JSON format, encoding issues, or server-side errors.

To fix this issue, you need to consider other issues with the server that might be causing the problem. Here are some steps that you can follow:

  1. Check the server-side code to ensure that the JSON response is correctly formatted. You can use a JSON validator tool to validate the response.

  2. Check if the response is being encoded correctly. If the response is not being encoded correctly, it can cause issues with the JSON parsing. You can use the header() function in PHP to set the correct encoding.

    header('Content-Type: application/json; charset=utf-8');
  3. Check if there are any server-side errors that might be causing the issue. You can use the network tools in your browser to check the response status and any error messages.

    $.ajax({
        url: 'your-api-url',
        dataType: 'json',
        success: function(response) {
            // handle success response
        },
        error: function(xhr, status, error) {
            console.log(xhr.status + ': ' + xhr.statusText);
            console.log('Error: ' + error);
        }
    });
  4. If the issue still persists, try using a different data format such as XML or plain text to see if the issue is related to JSON parsing.

    $.ajax({
        url: 'your-api-url',
        dataType: 'xml',
        success: function(response) {
            // handle success response
        },
        error: function(xhr, status, error) {
            console.log(xhr.status + ': ' + xhr.statusText);
            console.log('Error: ' + error);
        }
    });

By following these steps, you can identify and fix any issues with the server that might be causing the «parsererror» response from jQuery ajax request.

Been getting a «parsererror» from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.

My project is in MVC3 and I’m using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.

Dropdown: (this loads the «Views» from the list in the Viewbag and firing the event works fine)

@{
    var viewHtmls = new Dictionary<string, object>();
    viewHtmls.Add("data-bind", "value: ViewID");
    viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)

Javascript:

this.LoadViewContentNames = function () {
    $.ajax({
        url: '/Admin/Ajax/GetViewContentNames',
        type: 'POST',
        dataType: 'json',
        data: { viewID: $("#view").val() },
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            debugger;
            alert("Error");
        }
    });
};

The above code successfully calls the MVC method and returns:

[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
 {"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]

But jquery fires the error event for the $.ajax() method saying «parsererror».

Получил «parsererror» из jquery для запроса Ajax, я попытался изменить POST на GET, возвращая данные несколькими способами (создание классов и т.д.), но я не могу понять, что проблема есть.

Мой проект находится в MVC3, и я использую jQuery 1.5
У меня есть раскрывающийся список и в событии onchange я запускаю вызов, чтобы получить некоторые данные на основе того, что было выбрано.

Dropdown: (загружает «Views» из списка в Viewbag и срабатывает событие отлично)

@{
    var viewHtmls = new Dictionary<string, object>();
    viewHtmls.Add("data-bind", "value: ViewID");
    viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)

JavaScript:

this.LoadViewContentNames = function () {
    $.ajax({
        url: '/Admin/Ajax/GetViewContentNames',
        type: 'POST',
        dataType: 'json',
        data: { viewID: $("#view").val() },
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            debugger;
            alert("Error");
        }
    });
};

Вышеупомянутый код успешно вызывает метод MVC и возвращает:

[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
 {"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]

Но jquery вызывает событие ошибки для метода $.ajax(), говорящего «parsererror».

получал «parsererror» от jquery для запроса Ajax, я попытался изменить сообщение на GET, возвращая данные несколькими различными способами (создание классов и т. д.) но я не могу понять, в чем проблема.

мой проект находится в MVC3, и я использую jQuery 1.5
У меня есть раскрывающийся список, и в событии onchange я запускаю вызов, чтобы получить некоторые данные на основе того, что было выбрано.

выпадающий список: (это загружает «представления» из списка в Viewbag и стрельбы мероприятие отлично работает)

@{
    var viewHtmls = new Dictionary<string, object>();
    viewHtmls.Add("data-bind", "value: ViewID");
    viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)

Javascript:

this.LoadViewContentNames = function () {
    $.ajax({
        url: '/Admin/Ajax/GetViewContentNames',
        type: 'POST',
        dataType: 'json',
        data: { viewID: $("#view").val() },
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            debugger;
            alert("Error");
        }
    });
};

приведенный выше код успешно вызывает метод MVC и возвращает:

[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
 {"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]

но jquery запускает событие ошибки для $.метод ajax (), говорящий «parsererror».

14 ответов


Я недавно сталкивался с этой проблемой и наткнулся на этот вопрос.

я решил это гораздо более простым способом.

Способ Один

вы можете либо удалить dataType: 'json' свойство из литерала объекта…

Способ

или вы можете сделать то, что @Sagiv говорил, вернув свои данные как Json.

причина parserror сообщение происходит, когда вы просто вернуть строке или другое значение, это не реально Json, поэтому синтаксический анализатор не работает при его анализе.

Итак, если вы удалите dataType: json собственность, он не будет пытаться разобрать его как Json.

С другим методом, если вы обязательно вернете свои данные как Json парсер будет знать, как правильно ее обрабатывать.


посмотреть ответ @david-east для правильного способа справиться с проблемой

этот ответ имеет отношение только к ошибка с jQuery 1.5 при использовании файла: протокол.

недавно у меня была аналогичная проблема при обновлении до jQuery 1.5. Несмотря на получение правильного ответа обработчик ошибок уволен. Я решил это, используя complete событие, а затем проверка значения состояния. е.г:

complete: function (xhr, status) {
    if (status === 'error' || !xhr.responseText) {
        handleError();
    }
    else {
        var data = xhr.responseText;
        //...
    }
}

вы указали ответ вызова ajax тип as:

‘json’

где как фактический ответ ajax не является допустимым JSON, и в результате парсер JSON выдает ошибку.

лучший подход, который я бы порекомендовал изменить тип в:

‘text’

и в успешном обратном вызове проверьте, возвращается ли допустимый JSON или нет, и если проверка JSON терпит неудачу, предупредите его на экране, чтобы было очевидно, с какой целью вызов ajax на самом деле терпит неудачу. Взгляните на это:

$.ajax({
    url: '/Admin/Ajax/GetViewContentNames',
    type: 'POST',
    dataType: 'text',
    data: {viewID: $("#view").val()},
    success: function (data) {
        try {
            var output = JSON.parse(data);
            alert(output);
        } catch (e) {
            alert("Output is not valid JSON: " + data);
        }
    }, error: function (request, error) {
        alert("AJAX Call Error: " + error);
    }
});

проблема в том, что ваш контроллер возвращает строку или другой объект, который не может быть проанализирован.
вызов ajax ожидал получить JSON взамен. попробуйте вернуть JsonResult в контроллере так:

 public JsonResult YourAction()
    {
        ...return Json(YourReturnObject);

    }

надеюсь, что это помогает :)



есть много предложений снять

dataType: "json"

хотя я допускаю, что это работает, он игнорирует основную проблему. Если вы уверены, что возвращаемая строка действительно является JSON, то найдите блуждающие пробелы в начале ответа. Подумайте о том, чтобы взглянуть на него в fiddler. Моя выглядела так:—4—>

Connection: Keep-Alive
Content-Type: application/json; charset=utf-8

{"type":"scan","data":{"image":"./output/ou...

в моем случае это была проблема с PHP, извергающим нежелательные символы (в этом случае UTF-файл BOMs). Как только я удалил их, это исправило проблему, пока также сохраняя

dataType: json

убедитесь, что вы удалите любой отладочный код или что-либо еще, что может выводить непреднамеренную информацию. Несколько очевидно, но легко забывается в данный момент.


Я не знаю, если это все еще актуально, но проблема была с кодированием. Переход на ANSI решил проблему для меня.

0

автор: George Dgebuadze


Если вы получаете эту проблему с помощью HTTP GET in IE, я решил эту проблему, установив кэш: false.
Поскольку я использовал один и тот же url для запросов HTML и JSON, он попал в кэш вместо вызова json.

$.ajax({
    url: '/Test/Something/',
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: { viewID: $("#view").val() },
    success: function (data) {
        alert(data);
    },
    error: function (data) {
        debugger;
        alert("Error");
    }
});

вы должны удалить тип данных: «json». Тогда посмотри на магию… причина этого заключается в том, что вы конвертируете объект json в простую строку.. поэтому парсер JSON не смогла разобрать эту строку с JSON-объект.

this.LoadViewContentNames = function () {
$.ajax({
    url: '/Admin/Ajax/GetViewContentNames',
    type: 'POST',
    data: { viewID: $("#view").val() },
    success: function (data) {
        alert(data);
    },
    error: function (data) {
        debugger;
        alert("Error");
    }
 });
};

в случае операции Get из web .net mvc / api убедитесь, что вы разрешаете get

     return Json(data,JsonRequestBehavior.AllowGet);

Я также получал » возврат запроса с ошибкой: parsererror.»в консоли JavaScript.
В моем случае это не было вопросом Json, но я должен был передать в текстовую область просмотра допустимую кодировку.

  String encodedString = getEncodedString(text, encoding);
  view.setTextAreaContent(encodedString);

проблема

окно.формат JSON.синтаксический анализ вызывает ошибку в $.функция parseJSON.

<pre>
$.parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
</pre>

мое решение

перегрузка JQuery с помощью requirejs инструмент.

<pre>
define(['jquery', 'jquery.overload'], function() { 
    //Loading jquery.overload
});
</pre>

С помощью jQuery.перегрузка.содержимое файла js

<pre>
define(['jquery'],function ($) { 

    $.parseJSON: function( data ) {
        // Attempt to parse using the native JSON parser first
        /**  THIS RAISES Parsing ERROR
        if ( window.JSON && window.JSON.parse ) {
            return window.JSON.parse( data );
        }
        **/

        if ( data === null ) {
            return data;
        }

        if ( typeof data === "string" ) {

            // Make sure leading/trailing whitespace is removed (IE can't handle it)
            data = $.trim( data );

            if ( data ) {
                // Make sure the incoming data is actual JSON
                // Logic borrowed from http://json.org/json2.js
                if ( rvalidchars.test( data.replace( rvalidescape, "@" )
                    .replace( rvalidtokens, "]" )
                    .replace( rvalidbraces, "")) ) {

                    return ( new Function( "return " + data ) )();
                }
            }
        }

        $.error( "Invalid JSON: " + data );
    }

    return $;

});
</pre>

-1

автор: Christian MEROUR


если вы не хотите удалять/менять dataType: json, вы можете переопределить строгий синтаксический анализ jQuery, определив пользовательский converter:

$.ajax({
    // We're expecting a JSON response...
    dataType: 'json',

    // ...but we need to override jQuery's strict JSON parsing
    converters: {
        'text json': function(result) {
            try {
                // First try to use native browser parsing
                if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
                    return JSON.parse(result);
                } else {
                    // Fallback to jQuery's parser
                    return $.parseJSON(result);
                }
            } catch (e) {
               // Whatever you want as your alternative behavior, goes here.
               // In this example, we send a warning to the console and return 
               // an empty JS object.
               console.log("Warning: Could not parse expected JSON response.");
               return {};
            }
        }
    },

    ...

используя это, вы можете настроить поведение, когда ответ не может быть проанализирован как JSON (даже если вы получите пустое тело ответа!)

С помощью этого пользовательского конвертера,.done()/success будет срабатывать до тех пор, пока запрос был в противном случае успешным (код ответа 1xx или 2xx).


Been getting a «parsererror» from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.

My project is in MVC3 and I’m using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.

Dropdown: (this loads the «Views» from the list in the Viewbag and firing the event works fine)

@{
    var viewHtmls = new Dictionary<string, object>();
    viewHtmls.Add("data-bind", "value: ViewID");
    viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)

Javascript:

this.LoadViewContentNames = function () {
    $.ajax({
        url: '/Admin/Ajax/GetViewContentNames',
        type: 'POST',
        dataType: 'json',
        data: { viewID: $("#view").val() },
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            debugger;
            alert("Error");
        }
    });
};

The above code successfully calls the MVC method and returns:

[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
 {"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]

But jquery fires the error event for the $.ajax() method saying «parsererror».

This question is related to
javascript
c#
jquery
asp.net
json

I recently encountered this problem and stumbled upon this question.

I resolved it with a much easier way.

Method One

You can either remove the dataType: 'json' property from the object literal…

Method Two

Or you can do what @Sagiv was saying by returning your data as Json.


The reason why this parsererror message occurs is that when you simply return a string or another value, it is not really Json, so the parser fails when parsing it.

So if you remove the dataType: json property, it will not try to parse it as Json.

With the other method if you make sure to return your data as Json, the parser will know how to handle it properly.

See the answer by @david-east for the correct way to handle the issue

This answer is only relevant to a bug with jQuery 1.5 when using the file: protocol.

I had a similar problem recently when upgrading to jQuery 1.5. Despite getting a correct response the error handler fired. I resolved it by using the complete event and then checking the status value. e.g:

complete: function (xhr, status) {
    if (status === 'error' || !xhr.responseText) {
        handleError();
    }
    else {
        var data = xhr.responseText;
        //...
    }
}

You have specified the ajax call response dataType as:

‘json’

where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.

The best approach that I would recommend is to change the dataType to:

‘text’

and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:

$.ajax({
    url: '/Admin/Ajax/GetViewContentNames',
    type: 'POST',
    dataType: 'text',
    data: {viewID: $("#view").val()},
    success: function (data) {
        try {
            var output = JSON.parse(data);
            alert(output);
        } catch (e) {
            alert("Output is not valid JSON: " + data);
        }
    }, error: function (request, error) {
        alert("AJAX Call Error: " + error);
    }
});

the problem is that your controller returning string or other object that can’t be parsed.
the ajax call expected to get Json in return. try to return JsonResult in the controller like that:

 public JsonResult YourAction()
    {
        ...return Json(YourReturnObject);

    }

hope it helps :)

There are lots of suggestions to remove

dataType: "json"

While I grant that this works it’s ignoring the underlying issue. If you’re confident the return string really is JSON then look for errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:

Connection: Keep-Alive
Content-Type: application/json; charset=utf-8

{"type":"scan","data":{"image":".\/output\/ou...

In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping

dataType: json

Make sure that you remove any debug code or anything else that might be outputting unintended information. Somewhat obvious, but easy to forgot in the moment.

I have encountered such error but after modifying my response before sending it to the client it worked fine.

//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response);  // Sending to client

//Client side
success: function(res, status) {
    response = JSON.parse(res); // Getting as expected
    //Do something
}

I had the same problem, turned out my web.config was not the same with my teammates.
So please check your web.config.

Hope this helps someone.

I was also getting «Request return with error:parsererror.» in the javascript console.
In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.

  String encodedString = getEncodedString(text, encoding);
  view.setTextAreaContent(encodedString);

incase of Get operation from web .net mvc/api, make sure you are allow get

     return Json(data,JsonRequestBehavior.AllowGet);

I don’t know if this is still actual but problem was with Encoding. Changing to ANSI resolved the problem for me.

If you get this problem using HTTP GET in IE I solved this issue by setting the cache: false.
As I used the same url for both HTML and json requests it hit the cache instead of doing a json call.

$.ajax({
    url: '/Test/Something/',
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: { viewID: $("#view").val() },
    success: function (data) {
        alert(data);
    },
    error: function (data) {
        debugger;
        alert("Error");
    }
});

you should remove the dataType: «json». Then see the magic… the reason of doing such thing is that you are converting json object to simple string.. so json parser is not able to parse that string due to not being a json object.

this.LoadViewContentNames = function () {
$.ajax({
    url: '/Admin/Ajax/GetViewContentNames',
    type: 'POST',
    data: { viewID: $("#view").val() },
    success: function (data) {
        alert(data);
    },
    error: function (data) {
        debugger;
        alert("Error");
    }
 });
};

If you don’t want to remove/change dataType: json, you can override jQuery’s strict parsing by defining a custom converter:

$.ajax({
    // We're expecting a JSON response...
    dataType: 'json',

    // ...but we need to override jQuery's strict JSON parsing
    converters: {
        'text json': function(result) {
            try {
                // First try to use native browser parsing
                if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
                    return JSON.parse(result);
                } else {
                    // Fallback to jQuery's parser
                    return $.parseJSON(result);
                }
            } catch (e) {
               // Whatever you want as your alternative behavior, goes here.
               // In this example, we send a warning to the console and return 
               // an empty JS object.
               console.log("Warning: Could not parse expected JSON response.");
               return {};
            }
        }
    },

    ...

Using this, you can customize the behavior when the response cannot be parsed as JSON (even if you get an empty response body!)

With this custom converter, .done()/success will be triggered as long as the request was otherwise successful (1xx or 2xx response code).

The problem

window.JSON.parse raises an error in $.parseJSON function.

<pre>
$.parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
</pre>

My solution

Overloading JQuery using requirejs tool.

<pre>
define(['jquery', 'jquery.overload'], function() { 
    //Loading jquery.overload
});
</pre>

jquery.overload.js file content

<pre>
define(['jquery'],function ($) { 

    $.parseJSON: function( data ) {
        // Attempt to parse using the native JSON parser first
        /**  THIS RAISES Parsing ERROR
        if ( window.JSON && window.JSON.parse ) {
            return window.JSON.parse( data );
        }
        **/

        if ( data === null ) {
            return data;
        }

        if ( typeof data === "string" ) {

            // Make sure leading/trailing whitespace is removed (IE can't handle it)
            data = $.trim( data );

            if ( data ) {
                // Make sure the incoming data is actual JSON
                // Logic borrowed from http://json.org/json2.js
                if ( rvalidchars.test( data.replace( rvalidescape, "@" )
                    .replace( rvalidtokens, "]" )
                    .replace( rvalidbraces, "")) ) {

                    return ( new Function( "return " + data ) )();
                }
            }
        }

        $.error( "Invalid JSON: " + data );
    }

    return $;

});
</pre>

Понравилась статья? Поделить с друзьями:
  • Ошибка alternator workshop что обозначает
  • Ошибка airmatic w221
  • Ошибка alm fanuc
  • Ошибка airmatic visit workshop
  • Ошибка allowed memory size of