Ошибка ajax как исправить

Добрый вечер дорогие форумчане. Подскажите пожалуйста, почему при попытке отправить ajax запрос, у меня выскакивает alert из error??? Всю голову уже сломал, весь интернет уже перерыл.
2) И почему после того как я нажимаю ок в alert у меня перезагружается страница??

шаблон

{% extends "crm/main_struct.html" %}
{% load staticfiles %}

{% block content %}

<!--ОБЯЗАТЕЛЬНО СДЕЛАТЬ ФУНКЦИЮ НА JS КОТОРАЯ БУДЕТ ВЫЧИСЛЯТЬ ОТСТУПЫ И В НУЖНОЕ МЕСТО ПИХАТЬ КОНТЕНТ САЙТОВ-->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<script>
$(document).ready(function() {
  $('ul.tabs_m_w').each(function() {
    $(this).find('li').each(function(i) {
      $(this).click(function() {
        $(this).addClass('active').siblings().removeClass('active');
        var p = $(this).parents('div.tabs_container_m_w');
        p.find('div.tab_container_m_w').hide();
        p.find('div.tab_container_m_w:eq(' + i + ')').show();
      });
    });
  });
})
</script>
<a href="{{url}}/crm/my_work/new/" class="add_notebook_a">
    <div class="add_notebook">Добавить</div>
</a>
<div class="tabs_container_m_w">
  <ul class="tabs_m_w">
      {% for notebook in notebookList %}
        <li class="inl-bl_m_w">
            <div class="m_w_list_head">{{notebook.name}}</div>
            <div class="m_w_list_date">{{notebook.date_firstly}}</div>
            <div class="m_w_list_kr_info">{{notebook.kr_info}}</div>
        </li>
      {% endfor %}
  </ul>

    {% for notebook in notebookList %}
  <div class="tab_container_m_w">
      <a href="" onclick="resend({{notebook.id}});" class="a_tab">
          <div class="m_w_save">
            Сохранить
          </div>
      </a>
    <div class="m_w_info_head" id="name{{notebook.id}}" contentEditable="true">{{notebook.name}}</div>
      <div class="m_w_info_info" id="info{{notebook.id}}" contentEditable="true">{{notebook.information}}</div>
  </div>
{% endfor %}

</div>

<script>
    function resend(pk){
           var name = document.getElementById('name' + pk).innerHTML.trim().replace(/<.*?>/g, "");
           var info = document.getElementById('info' + pk).innerHTML.trim().replace(/<.*?>/g, "");
           edit(name, info, pk);
    }
</script>

<script>
function edit(name, info, pk) {
// Если поля заполнены, отправляем их значения
        $.ajax({
            error: function() {
                alert('Ошибка получения запроса');
            },
    // При успехе очищаем поля и меняем кнопочку
                success: function(data) {
                 alert("Успех"); // для проверки, что скрипт работает
                },
    // CSRF механизм защиты Django
                beforeSend: function(xhr, settings) {
                    console.log('-------------before send--');
                    function getCookie(name) {
                        var cookieValue = null;
                        if (document.cookie && document.cookie != '') {
                            var cookies = document.cookie.split(';');
                            for (var i = 0; i < cookies.length; i++) {
                                var cookie = jQuery.trim(cookies[i]);
                                // Does this cookie string begin with the name we want?
                            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                                break;
                            }
                        }
                    }
                    return cookieValue;
                    }
                    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                        // Only send the token to relative URLs i.e. locally.
                        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                    }
                }
            });// ajax


        return false;
    };
</script>
{% endblock %}

urls.py

urlpatterns = patterns('',
    url(r'^my_work/edit/$', views.NBEdit, name='crm_edit_NB'),
)

views.py

def NBEdit(request):
    if request.is_ajax():
        for i in MyDela.objects.filter(pk=request.POST.get("id", "")):
            i.name = request.POST.get("name", "")[:250]
            i.information = request.POST.get("info", "")
            i.save()
        #  return HttpResponse("ok")
        return HttpResponseRedirect('/crm/sites/')
    else:
        #  return HttpResponse("bad")
        return HttpResponseRedirect('/crm/zayvki/')

Прошу не кидаться помидорами, я только учусь кодить))

Let’s say I have the following jQuery AJAX call:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
        // Do stuff
   }
 });

Now, when this AJAX call is made I want the server-side code to run through a few error handling checks (e.g. is the user still logged in, do they have permission to use this call, is the data valid, etc). If an error is detected, how do I bubble that error message back up to the client side?

My initial thought would be to return a JSON object with two fields: error and errorMessage. These fields would then be checked in the jQuery AJAX call:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
       if (result.error == "true") 
       {
           alert("An error occurred: " & result.errorMessage);
       }
       else 
       {
           // Do stuff
       }
   }
 });

This feels a bit clunky to me, but it works. Is there a better alternative?

Цитата:

Время выполнения установить 30-60 секунд.
Памяти установить 64 Мб Установить MBString!

Если я вас правильно понял, то ресурсов хватает вроде как:
(библиотека MBString подключена)
Цитата:

;;;;;;;;;;;;;;;;;;;
; Resource Limits ;
;;;;;;;;;;;;;;;;;;;

max_execution_time = 130     ; Maximum execution time of each script, in seconds
max_input_time = 160   ; Maximum amount of time each script may spend parsing request data
max_input_nesting_level = 64 ; Maximum input variable nesting level
memory_limit = 128M      ; Maximum amount of memory a script may consume (128MB)

error.log
Цитата:

[Tue Sep 18 18:39:09 2012] [error] [client 127.0.0.1] File does not exist: C:/WebServers/www/cms.ru/favicon.ico
[Tue Sep 18 18:39:09 2012] [error] [client 127.0.0.1] File does not exist: C:/WebServers/www/cms.ru/favicon.ico

Забудьте про javascript alert! Все сообщения пользователю должны быть оформлены в соответствии с темой оформления вашего сайта. Никаких системных окон. Пользователи их боятся.

В друпал 7 есть замечательный AJAX Framework. Но разработчики сделали, что все ошибки в его работе (а они могут случиться на ровном месте), вываливаются на пользователя в виде javascript alert окна.

На английском это сообщение выглядит так:

An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /system/ajax
StatusText:
ResponseText:
ReadyState: 4

Такая ошибка часто появляется, когда ajax запрос еще продолжается (сервер делает какую-нить долгую работу), крутится индикатор работы, а пользователь нажал на ссылку на странице, чтобы с нее уйти.

Я придерживаюсь внутреннего убеждения, что выводить сообщения для пользователя с помощью alert’ов — это моветон. Они некрасивые, они выглядят по-разному в разных браузерах и операционных системах и они пугают пользователя. В общем один негатив.

Именно поэтому, мы все алерты будем выводить в консоль браузера (если она есть).

Для этого в любой javascript файл (например в нашей drupal теме или в собственном модуле) добавляем следующую строчку:

window.alert = function(arg) { if (window.console && console.log) { console.log(arg);}};

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

Let’s say I have the following jQuery AJAX call:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
        // Do stuff
   }
 });

Now, when this AJAX call is made I want the server-side code to run through a few error handling checks (e.g. is the user still logged in, do they have permission to use this call, is the data valid, etc). If an error is detected, how do I bubble that error message back up to the client side?

My initial thought would be to return a JSON object with two fields: error and errorMessage. These fields would then be checked in the jQuery AJAX call:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
       if (result.error == "true") 
       {
           alert("An error occurred: " & result.errorMessage);
       }
       else 
       {
           // Do stuff
       }
   }
 });

This feels a bit clunky to me, but it works. Is there a better alternative?

Can you post the signature of your method that is supposed to accept this post?

Additionally I get the same error message, possibly for a different reason. My YSOD talked about the dictionary not containing a value for the non-nullable value.
The way I got the YSOD information was to put a breakpoint in the $.ajax function that handled an error return as follows:

<script type="text/javascript" language="javascript">
function SubmitAjax(url, message, successFunc, errorFunc) {
    $.ajax({
        type:'POST',
        url:url,
        data:message,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success:successFunc,
        error:errorFunc
        });

};

Then my errorFunc javascript is like this:

function(request, textStatus, errorThrown) {
        $("#install").text("Error doing auto-installer search, proceed with ticket submissionn"
        +request.statusText); }

Using IE I went to view menu -> script debugger -> break at next statement.
Then went to trigger the code that would launch my post. This usually took me somewhere deep inside jQuery’s library instead of where I wanted, because the select drop down opening triggered jQuery. So I hit StepOver, then the actual next line also would break, which was where I wanted to be. Then VS goes into client side(dynamic) mode for that page, and I put in a break on the $("#install") line so I could see (using mouse over debugging) what was in request, textStatus, errorThrown. request. In request.ResponseText there was an html message where I saw:

<title>The parameters dictionary contains a null entry for parameter 'appId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ContentResult CheckForInstaller(Int32)' in 'HLIT_TicketingMVC.Controllers.TicketController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>

so check all that, and post your controller method signature in case that’s part of the issue

Can you post the signature of your method that is supposed to accept this post?

Additionally I get the same error message, possibly for a different reason. My YSOD talked about the dictionary not containing a value for the non-nullable value.
The way I got the YSOD information was to put a breakpoint in the $.ajax function that handled an error return as follows:

<script type="text/javascript" language="javascript">
function SubmitAjax(url, message, successFunc, errorFunc) {
    $.ajax({
        type:'POST',
        url:url,
        data:message,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success:successFunc,
        error:errorFunc
        });

};

Then my errorFunc javascript is like this:

function(request, textStatus, errorThrown) {
        $("#install").text("Error doing auto-installer search, proceed with ticket submissionn"
        +request.statusText); }

Using IE I went to view menu -> script debugger -> break at next statement.
Then went to trigger the code that would launch my post. This usually took me somewhere deep inside jQuery’s library instead of where I wanted, because the select drop down opening triggered jQuery. So I hit StepOver, then the actual next line also would break, which was where I wanted to be. Then VS goes into client side(dynamic) mode for that page, and I put in a break on the $("#install") line so I could see (using mouse over debugging) what was in request, textStatus, errorThrown. request. In request.ResponseText there was an html message where I saw:

<title>The parameters dictionary contains a null entry for parameter 'appId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ContentResult CheckForInstaller(Int32)' in 'HLIT_TicketingMVC.Controllers.TicketController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>

so check all that, and post your controller method signature in case that’s part of the issue

This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.

Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:

$.ajax({
     url: 'does-not-exist.php',
     success: function(returnData){
         var res = JSON.parse(returnData);
     },
     error: function(xhr, status, error){
         var errorMessage = xhr.status + ': ' + xhr.statusText
         alert('Error - ' + errorMessage);
     }
});

If you look at the code above, you will notice that I have two functions:

  • success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
  • error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.

The Ajax error function has three parameters:

  • jqXHR
  • textStatus
  • errorThrown

In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:

  • status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
  • statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.

Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.

JQuery 3.0: The error, success and complete callbacks are deprecated.

Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.

An example of done and fail being used:

$.ajax("submit.php")
  .done(function(data) {
      //Ajax request was successful.
  })
  .fail(function(xhr, status, error) {
      //Ajax request failed.
      var errorMessage = xhr.status + ': ' + xhr.statusText
      alert('Error - ' + errorMessage);
})

Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.

Hopefully, you found this tutorial to be useful.

  1. Главная
  2. Форумы
  3. Техподдержка Drupal
  4. Решение проблем

Главные вкладки

  • Просмотр(активная вкладка)
  • Реакции

Аватар пользователя wiom


12 января 2014 в 4:09

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

Возникла AJAX HTTP ошибка.
Полученный код HTTP: 200
Следует отладочная информация.
Путь: /system/ajax
Текст Состояния: OK
Текст Ответа: [{«command»:«settings»,«settings»:{«basePath»:«/«,«pathPrefix»:«»,«ajaxPageState»:
{«theme»:«seven»,«theme_token»:«2J3KowjLFRBatAqM6DA5Gftwh4MXFLJszqC2MgEY5Zk»},«quote_nest»:«2»,«ajax»:{«edit-fields-field-img-
settings-edit-form-actions-save-settings»
:{«callback»:«field_ui_display_overview_multistep_js»,«wrapper»:«field-display-overview-
wrapper»
,«effect»:«fade»,«event»:«mousedown»,«keypress»:true,«prevent»:«click»,«url»:«/system/ajax»,«submit»:
{«_triggering_element_name»:«field_img_formatter_settings_update»,«_triggering_element_value»:«u041eu0431u043du043eu0432u0438
u0442u044c»
}},«edit-fields-field-img-settings-edit-form-actions-cancel-settings»:
{«callback»:«field_ui_display_overview_multistep_js»,«wrapper»:«field-display-overview-
wrapper»
,«effect»:«fade»,«event»:«mousedown»,«keypress»:true,«prevent»:«click»,«url»:«/system/ajax»,«submit»:
{«_triggering_element_name»:«field_img_formatter_settings_cancel»,«_triggering_element_value»:«u041eu0442u043cu0435u043du0438
u0442u044c»
}}},«fieldUIRowsData»:{«body»:
{«rowHandler»:«field»,«defaultFormatter»:«text_default»,«name»:«body»,«region»:«visible»},«field-img»:
{«rowHandler»:«field»,«defaultFormatter»:«image»,«name»:«field_img»,«region»:«visible»},«subscriptions-ui»:
{«rowHandler»:«field»,«name»:«subscriptions_ui»,«region»:«visible»},«-add-new-group»:
{«rowHandler»:«group»,«name»:«_add_new_group»,«region»:«add_new»}}},«merge»:true},
{«command»:«insert»,«method»:null,«selector»:null,«data»:«u003Cdiv id=u0022field-display-overview-wrapperu0022u003Eu003Ctable
class=u0022field-ui-overview sticky-enabledu0022 id=u0022field-display-overviewu0022u003En
u003Ctheadu003Eu003Ctru003Eu003Cthu003Eu041fu043eu043bu0435u003C/thu003Eu003Cthu003Eu0412u0435u0441u003C/thu00
3Eu003Cthu003Eu0420u043eu0434u0438u0442u0435u043bu044cu003C/thu003Eu003Cthu003Eu041cu0435u0442u043au0430u003C
/thu003Eu003Cth colspan=u00223u0022u003Eu0424u043eu0440u043cu0430u0442u003C/thu003E
u003C/tru003Eu003C/theadu003Enu003Ctbodyu003En u003Ctr class=u0022region-message region-visible-message region-
populatedu0022u003Eu003Ctd colspan=u00227u0022u003Eu041fu043eu043bu0435u0439 u043du0435u0442.u003C/tdu003E
u003C/tru003En u003Ctr class=u0022draggable tabledrag-leaf field-formatter-settings-editing oddu0022 id=u0022field-
imgu0022u003Eu003Ctdu003Eu041au0430u0440u0442u0438u043du043au0430u003C/tdu003Eu003Ctdu003Eu003Cdiv
class=u0022form-item form-type-textfield form-item-fields-field-img-weightu0022u003En  u003Clabel class=u0022element-
invisibleu0022 for=u0022edit-fields-field-img-weight—2u0022u003Eu0412u0435u0441
u041au0430u0440u0442u0438u043du043au0430 u003C/labelu003En u003Cinput class=u0022field-weight form-textu0022
type=u0022textu0022 id=u0022edit-fields-field-img-weight—2u0022 name=u0022fields[field_img][weight]u0022 value=u00220u0022
size=u00223u0022 maxlength=u0022128u0022 /u003Enu003C/divu003Enu003C/tdu003Eu003Ctdu003Eu003Cdiv class=u0022form-
item form-type-select form-item-fields-field-img-parentu0022u003En  u003Clabel class=u0022element-invisibleu0022
for=u0022edit-fields-field-img-parent—2u0022u003Eu041eu0442u043eu0431u0440u0430u0436u0430u0435u043cu0430u044f
u043cu0435u0442u043au0430 u0434u043bu044f u041au0430u0440u0442u0438u043du043au0430 u003C/labelu003En
u003Cselect class=u0022field-parent form-selectu0022 id=u0022edit-fields-field-img-parent—2u0022 name=u0022fields[field_img]
[parent]u0022u003Eu003Coption value=u0022u0022 selected=u0022selectedu0022u003E- u041du0435
u0443u043au0430u0437u0430u043du043e —u003C/optionu003Eu003Coption
value=u0022_add_new_groupu0022u003Eu0414u043eu0431u0430u0432u0438u0442u044c u043du043eu0432u0443u044e
u0433u0440u0443u043fu043fu0443u003C/optionu003Eu003C/selectu003Enu003C/divu003Enu003Cinput class=u0022field-
nameu0022 type=u0022hiddenu0022 name=u0022fields[field_img][parent_wrapper][hidden_name]u0022 value=u0022field_imgu0022
/u003Enu003C/tdu003Eu003Ctdu003Eu003Cdiv class=u0022form-item form-type-select form-item-fields-field-img-
labelu0022u003En  u003Clabel class=u0022element-invisibleu0022 for=u0022edit-fields-field-img-label-
-2u0022u003Eu041eu0442u043eu0431u0440u0430u0436u0430u0435u043cu0430u044f u043cu0435u0442u043au0430
u0434u043bu044f u041au0430u0440u0442u0438u043du043au0430 u003C/labelu003En u003Cselect id=u0022edit-fields-field-
img-label—2u0022 name=u0022fields[field_img][label]u0022 class=u0022form-selectu0022u003Eu003Coption
value=u0022aboveu0022u003Eu0421u0432u0435u0440u0445u0443u003C/optionu003Eu003Coption
value=u0022inlineu0022u003Eu0412 u043bu0438u043du0438u044eu003C/optionu003Eu003Coption value=u0022hiddenu0022
selected=u0022selectedu0022u003Eu0026lt;u0421u043au0440u044bu0442u043eu0026gt;u003C/optionu003Eu003C/selectu003En
u003C/divu003Enu003C/tdu003Eu003Ctd colspan=u00223u0022u003Eu003Cdiv class=u0022ajax-new-contentu0022u003Eu003Cdiv
class=u0022form-item form-type-select form-item-fields-field-img-typeu0022u003En  u003Clabel class=u0022element-
invisibleu0022 for=u0022edit-fields-field-img-type—2u0022u003Eu0417u0430u0434u0430u043du0438u0435
u0444u043eu0440u043cu0430u0442u0430 u0434u043bu044f u041au0430u0440u0442u0438u043du043au0430
u003C/labelu003En u003Cselect class=u0022field-formatter-type form-selectu0022 id=u0022edit-fields-field-img-type—2u0022
name=u0022fields[field_img][type]u0022u003Eu003Coption value=u0022imageu0022
selected=u0022selectedu0022u003Eu0418u0437u043eu0431u0440u0430u0436u0435u043du0438u0435u003C/optionu003Eu003Copti
on
value=u0022hiddenu0022u003Eu0026lt;u0421u043au0440u044bu0442u043eu0026gt;u003C/optionu003Eu003C/selectu003Enu003
C/divu003Enu003Cdiv class=u0022field-formatter-settings-edit-form form-wrapperu0022 id=u0022edit-fields-field-img-settings-
edit-formu0022u003Eu041du0430u0441u0442u0440u043eu0439u043au0438 u0444u043eu0440u043cu0430u0442u0430: u003Cspan
class=u0022formatter-nameu0022u003Eu0418u0437u043eu0431u0440u0430u0436u0435u043du0438u0435u003C/spanu003Eu003Cdiv
class=u0022form-item form-type-select form-item-fields-field-img-settings-edit-form-settings-image-styleu0022u003En  
u003Clabel for=u0022edit-fields-field-img-settings-edit-form-settings-image-styleu0022u003Eu0421u0442u0438u043bu044c
u0438u0437u043eu0431u0440u0430u0436u0435u043du0438u044f u003C/labelu003En u003Cselect id=u0022edit-fields-field-
img-settings-edit-form-settings-image-styleu0022 name=u0022fields[field_img][settings_edit_form][settings][image_style]u0022
class=u0022form-selectu0022u003Eu003Coption value=u0022u0022 selected=u0022selectedu0022u003Eu041du0435u0442
(u043eu0440u0438u0433u0438u043du0430u043bu044cu043du043eu0435
u0438u0437u043eu0431u0440u0430u0436u0435u043du0438u0435)u003C/optionu003Eu003Coption
value=u0022avataru0022u003Eavataru003C/optionu003Eu003Coption value=u0022thumbnailu0022u003EThumbnail
(100×100)u003C/optionu003Eu003Coption value=u0022mediumu0022u003EMedium (220×220)u003C/optionu003Eu003Coption
value=u0022largeu0022u003ELarge (480×480)u003C/optionu003Eu003C/selectu003Enu003C/divu003Enu003Cdiv
class=u0022form-item form-type-select form-item-fields-field-img-settings-edit-form-settings-image-linku0022u003En  u003Clabel
for=u0022edit-fields-field-img-settings-edit-form-settings-image-
linku0022u003Eu0418u0437u043eu0431u0440u0430u0436u0435u043du0438u0435 u043au0430u043a
u0441u0441u044bu043bu043au0430 u043du0430 u003C/labelu003En u003Cselect id=u0022edit-fields-field-img-settings-edit-
form-settings-image-linku0022 name=u0022fields[field_img][settings_edit_form][settings][image_link]u0022 class=u0022form-
selectu0022u003Eu003Coption value=u0022u0022
selected=u0022selectedu0022u003Eu041du0438u0447u0435u0433u043eu003C/optionu003Eu003Coption
value=u0022contentu0022u003Eu0421u043eu0434u0435u0440u0436u0438u043cu043eu0435u003C/optionu003Eu003Coption
value=u0022fileu0022u003Eu0424u0430u0439u043bu003C/optionu003Eu003C/selectu003Enu003C/divu003Enu003Cdiv
class=u0022form-actions form-wrapperu0022 id=u0022edit-fields-field-img-settings-edit-form-actionsu0022u003Eu003Cinput
type=u0022submitu0022 id=u0022edit-fields-field-img-settings-edit-form-actions-save-settingsu0022
name=u0022field_img_formatter_settings_updateu0022 value=u0022u041eu0431u043du043eu0432u0438u0442u044cu0022
class=u0022form-submitu0022 /u003Eu003Cinput type=u0022submitu0022 id=u0022edit-fields-field-img-settings-edit-form-
actions-cancel-settingsu0022 name=u0022field_img_formatter_settings_cancelu0022
value=u0022u041eu0442u043cu0435u043du0438u0442u044cu0022 class=u0022form-submitu0022
/u003Eu003C/divu003Eu003C/divu003Eu003C/divu003Eu003C/tdu003E u003C/tru003En u003Ctr class=u0022draggable
tabledrag-leaf evenu0022
id=u0022bodyu0022u003Eu003Ctdu003Eu0422u0435u043au0441u0442u003C/tdu003Eu003Ctdu003Eu003Cdiv class=u0022form-item
form-type-textfield form-item-fields-body-weightu0022u003En  u003Clabel class=u0022element-invisibleu0022 for=u0022edit-
fields-body-weight—2u0022u003Eu0412u0435u0441 u0422u0435u043au0441u0442 u003C/labelu003En u003Cinput
class=u0022field-weight form-textu0022 type=u0022textu0022 id=u0022edit-fields-body-weight—2u0022 name=u0022fields[body]
[weight]u0022 value=u00221u0022 size=u0022

Не могу понять в чем дело, в гугле искал решение, много что нашел, и что F5 нужно просто нажать, увеличить memory, которая у меня и так 128MB от хостера, и что в файле local.inc нужно увеличить время ответа скриптов, но ничего не помогло. Подскажите что нибудь, пожалуйста.

  • Drupal7
  • Есть вопрос
  • Решение проблем

11: Обработка ошибок в JavaScript

Вы написали приложение JavaScript, и оно работает отлично — пока вы не получите сообщение об ошибке. Это нечто неприглядное, выскакивающее на экране, что-нибудь вроде ‘myObject.fields is null or not an object’. Что это значит? В этом уроке мы рассмотрим, как избавиться от ошибок, и покажем несколько различных методов для общей обработки ошибок.

Синтаксические ошибки

JavaScript имеет два основных уровня обработки ошибок: синтаксические ошибки и ошибки времени выполнения. Синтаксические ошибки возникают до выполнения кода JavaScript, означая в основном, что код невозможно компилировать. Возьмем, например, следующий код:

for(var i=0; i<10; i++)
  // рабочий код здесь 
}

Обратите внимание, что здесь пропущена открывающая скобка {. Если попробовать выполнить этот код, то немедленно появится сообщение об ошибке, даже если код находится в функции, которая не выполняется сразу. Такие ошибки почти всегда легко находятся и исправляются. В этом случае будет получено сообщение, говорящее что-нибудь подобное » Ожидалась ‘)’, строка 10, позиция 18«. Если перейти к строке 10, то там обычно будет находиться достаточно очевидная ошибка, такая, как пропущенная ), дополнительный знак <или какая-то другая опечатка. С такими ошибками ничего нельзя сделать, кроме как просто исправить и двигаться дальше. Ниже представлен список некоторых наиболее распространенных синтаксических ошибок:

  • Пропущенные или непарные фигурные, круглые или квадратные скобки

    Каждая фигурная {, круглая (, или квадратная [ скобка должна иметь свою закрывающую парную скобку. Если имеются вложенные скобки, то внутренние должны быть закрыты прежде, чем внешние. Например, набор скобок {[}] является недопустимым.

    Условия операторов if, for и while должны помещаться в круглые скобки. Выражнение «if x=5{» является недопустимым, так как «x=5» должно быть заключено в круглые скобки. Если с этим возникнут проблемы, то существуют редакторы, такие, как EditPlus, которые могут выделять соответствующие пары скобок, и т.д.

  • Пропущенные или непарные кавычки

    Это очень распространенная проблема. Строки в JavaScript начинаются символом или « и должны заканчиваться таким же символом. Если этот символ существует в строке, то он должен быть экранирован. Например, код

    var x = 'It's a beautiful day';
    

    является недопустимым, потому что в It’s не экранировано. Этот код должен выглядеть следующим образом:

    var x = 'It's a beautiful day';
    
    // или
    
    var x = "It's a beautiful day";
    

    Еще одной достаточно распространенной ошибкой является завершение строки другим символом, т.е.:

    var x = "It's a beautiful day';
    

    Эта строка начинается с символа «, поэтому должна закончиться также символом «.

  • Пропущенная точка с запятой

    Хотя точки с запятой обычно не нужны в JavaScript, но лучше все же их использовать. Например, если нужно сократить файл JavaScript, то обычно удаляют все переносы строк. Возьмем следующий код:

    Если удалить переносы строк, то получим код

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

Ошибки времени выполнения

Перейдем к ошибкам времени выполнения. После запуска кода на исполнение начинают появляться ошибки времени выполнения. Эти ошибки могут возникать в связи с множеством причин. Каждый из следующих далее блоков кода будет порождать ошибку:

alert(x); // 'x' не определено 

var x;

x[5] = 'test'; // 'x' будет null или не является объектом 


window.frames = 5; //  Не реализовано 


var for; // ожидается идентификатор 

document.doesNotExist(5);
// объект не поддерживает это свойство или метод 


alert(parseInt('5')); // ожидается объект 

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

  • Неправильное использование прописных букв

    Все встроенные функции JavaScript используют специальную форму записи имен функций, предполагающую, что имя функции начинается со строчной буквы, а в начале каждого следующего слова будет использоваться прописная буква: parseInt, getElementById, createElement, appendChild, и т.д.

    Так как JavaScript учитывает регистр символов, то неправильный ввод имени одной из этих функций часто будет приводить к ошибке во время выполнения.

  • Ссылка на несуществующий код, функции или объекты DOM

    Эта проблема возникает обычно в отношении объектов DOM. Предположим, что имеется код, который изменяет некоторые элементы формы на странице. Если делается попытка выполнить этот код до появления элементов формы, например, если поместить его в тег <HEAD>, то будет получена ошибка JavaScript.

    Обычно эта проблема легко решается. Лучшим решением будет выполнение кода по событию onload, например:

    <BODY onload="loadFunction();">
    

    или еще лучше, присоединение события к загрузке тела.

  • Использование зарезервированного слова

    Существует длинный список зарезервированных ключевых слов JavaScript. Если делается попытка использовать многие из них вне их специального контекста, как, например, запись

    то будет возникать ошибка.

  • Использование пропущенного параметра

    При определении функции обычно используется некоторое количество аргументов. Если некоторые из этих аргументов пропущены и делается попытка их использовать, то возникнут ошибки.

Большинство из этих проблем попадают в категорию опечаток и просто обычных ошибок, которые можно исправить, но необходимо о них знать, чтобы случайно не сделать.

Однако последний тип ошибки из этого списка с пропущенными параметрами можно проверить достаточно легко:

function myFunction(a, b, c){
  if(a){
    // выполняется работа с a
  }
  if(b && c){
    // выполняется работа с b и c
  }
}

Если функция вызывается только с одной переменной, то проблемы не возникает. Однако надо помнить об одной вещи: если входящая по значению переменная может быть определена как false (0 или false), то код не будет работать. В связи с этим лучше проверять, что переменная не была определена:

function myFunction(a, b, c){
  if(typeof(a)!='undefined'){
    // выполнение кода с a
  }
  if((typeof(b)!='undefined') && (typeof(c)!='undefined')){
    // выполнение кода с b и c
  }
}

В этом случае, даже если одна из переменных будет передана как 0, false или null, код все равно будет работать.

Сейчас мы перейдем к изучению механизмов обработок ошибок — с помощью операторов Try/Catch и функции window.onerror.

window.onerror

Откровенно говоря, функция window.onerror имеет небольшую практическую пользу. Ее чаще всего используют для полного отключения всех сообщений об ошибках во время выполнения:

window.onerror = function(){
  return true;
}

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

Функцию window.onerror можно также использовать для вывода пользователям несколько более дружественных сообщений об ошибках. Можно просто вывести, например, сообщение ‘Произошла ошибка, свяжитесь, пожалуйста, с Web-мастером’, вместо вывода пользователю всех технических деталей ошибки (что большинство браузеров делает по умолчанию).

Еще одно использование window.onerror состоит в отправке разработчику списка всех ошибок, произошедших на сайте. Можно использовать AJAX для отправки сообщений об ошибках в форме, чтобы можно было позже их исправить. Все это возможно сделать неявно, без взаимодействия с пользователем.

Try/Catch/Finally и Throw

Операторы Try/Catch являются несомненно наиболее распространенным и обычно лучшим способом реализовать обработку ошибок в JavaScript. Но не только это — операторы Try/Catch могут иногда быть единственным способом реализовать некоторые задачи, такие, как обнаружение объекта. Возьмем, например, простую функцию для создания в Internet Explorer объекта XMLHttp:

var activeXObjects = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0',
'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
for(var i=0; i<activeXObjects.length; i++){
  try{
    return new ActiveXObject(activeXObjects[i]);
  }catch(err){}
}

Заранее неизвестно, какие объекты установил пользователь, и, к сожалению, браузер не предоставляет никакого механизма это определить. Поэтому остается создавать каждый из 6 возможных объектов, пока один из них (будем надеяться) не заработает.

Операторы Try/Catch можно использовать для перехвата ошибок двух типов: ошибок времени выполнения и ошибок пользователя. Ошибки времени выполнения, как говорилось ранее, возникают, когда у компилятора JavaScript существует проблема с созданным кодом. Ошибки пользователя, с другой стороны, будут технически проходить без проблем, но возникают в связи с контекстом приложения. Если имеется поле, в которое пользователь, например, должен ввести свой возраст, и пользователь вводит -2, то это приводит к появлению ошибки.

Блок Try/Catch имеет достаточно простой синтаксис:

try{
  // код 
}catch(err){
  // код обработки ошибки 
}

Если код в блоке try приводит к ошибке, то сценарий немедленно переходит в блок catch. Объект ошибки » err» в JavaScript имеет ряд полезных свойств — описание, сообщение, имя и номер, которые можно использовать для вывода информации о том, что произошло:

try{
  var x;
  x[5] = 5;
}catch(err){
  alert('An error occured: '+err.description);
}

Если в операторе catch окажется ошибка, то JavaScript сможет обратиться в дальнейшем к ее описанию.

Такой блок кода Try/Catch можно применять в любом месте. Однако, обычно, код должен быть написан таким образом, чтобы это не нужно было использовать, — в частности, весь ввод должен проверяться.

Блок Try/Catch можно применять также для создания своих собственных ошибок:

function setAge(x){
  if(typeof(x)=='undefined') throw('Вы должны ввести возраст');
  if(typeof(x)!='number') throw('Возраст должен быть числом');
  if(x<0) throw('Возраст не может быть меньше 0');
  if(x>120) throw('Возраст не может быть больше 120');

  var myAge = x;

  // еще код 
}

try{
  setAge(userInput);
}catch(err){
  alert(err);
}

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

Блок try/catch имеет еще одну часть, оператор «finally«:

try{
  // код 
}catch(err){
  // код 
}finally{
  // код 
}

Код в «завершающем блоке» будет выполняться независимо от того, что происходит с операторами Try/Catch. В чем же разница между завершающим блоком и простым размещением кода после блока try/catch? В большинстве случаев никакой разницы не будет. Однако, если блок try/catch находится в функции и происходит выход из функции в блоке try или catch, то возникнет существенное различие:

function myFunction(){
  try{
    return someValue;
  }catch(err){
    return defaultValue;
  }finally{
    alert('finally!');
  }

  alert('End!');
}

В этом случае оба блока try и catch возвращают значение. Мы получим сообщение «finally!«, но не получим сообщение «End!«, потому что произойдет выход из функции до сообщения alert(‘End!’). То же самое остается справедливым для операторов Try/Catch, которые осуществляют выход из тела цикла for или while, например:

for(var i=0; i<10; i++){
  try{
    if(i==5) continue;
  }catch(err){
    // обработка ошибки 
  }finally{
    // код 
  }

  // еще код 
}

Обработка ошибок в AJAX

Запросы XMLHttp, рассмотренные в предыдущей лекции, могут иметь совершенно другой тип ошибки: данные просто не проходят. Это можно проверить через статус объекта XMLHttp:

function processingFunction(){
  if(oXml.readyState!=4) return; // запрос не выполнен 

  switch(oXml.status){
    case 0: case 200:  // запрос выполнен 
      break;
    case 408: case 504: // запрос превысил время ожидания 
      // код 
      break;
    default: // ошибка запроса 
      // код
      return; // возможно, вы захотите выйти 
      break;
  }

  // продолжение обработки запроса 
}

oXml в этом примере является объектом XMLHttp, а функция processingFunction была присоединена к свойству onreadystatechange этого объекта.

Проверяя код статуса, мы узнаем, был ли запрос обработан успешно. Код 200 является в HTTP стандартным кодом статуса «Все прошло нормально» . Код 0 возникает при загрузке файлов из локальной файловой системы (если для этого есть соответствующие полномочия). Статус код 0 часто возникает при локальном тестировании приложения.

Коды статуса 408 и 504 представляют ситуацию с превышением времени ожидания. Очень часто это указывает на сетевые проблемы, и простое повторение запроса может разрешить проблему. Однако отметим, что эти коды представляют также слишком длительную работу сервера над ответом. Например, если существует ошибка сценария на сервере, которая приводит к бесконечному циклу, то может возникнуть код ошибки 408 или 504. В этом случае повторная попытка будет вредоносной, поэтому надо быть осторожным. Самым безопасным является уведомление пользователя и выход из функции, но это не очень корректно по отношению к пользователю.

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

Это почти все об обработке ошибок в JavaScript. Имеет смысл включать в функции обработку ошибок, но, возможно, что это не требуется для каждой функции или каждого фрагмента кода. В большинстве ситуаций достаточно проверки ввода пользователей. Для реализации проверки пользователя наиболее полезным средством является использование блоков Try/Catch/Throw.

В следующей лекции будет рассмотрена рекурсия:

«Чтобы понять рекурсию, сначала необходимо понять рекурсию».

jQuery is the most awesome javascript library that exists. Every day, I’m finding new ways to leverage it and shorter, more efficient ways to get things done. But, while most things are easy to do, the solution is not always immediately evident. One of the things that took me a good while to figure out was how to gracefully handle AJAX errors. Anyone who’s worked with JSON requests and other AJAX calls knows that sometimes, that stuff just fails silently; you know something went wrong, but no errors were thrown. If it wasn’t for FireBug showing us 404 or 500 style errors, there’d be no evidence at all of these fails.

I’ve come up with a way to centralize my AJAX calls in a way that seemlessly handles all errors that occur either from the request connection or the JSON processing (ie. poorly formed JSON that cannot be converted back into Javascript data types). I’m not sure if this is the best of all ways, but I’m liking it. The whole concept rests on the fact that all of my system API (AJAX) calls return a uniform response with the following structure:

{
	SUCCESS: true,
	DATA: "",
	ERRORS: []
}

The Success property flags the request as having executed properly and returned the expected data. The Data property can be anything it needs to be. The Errors property is an array of any errors that need to be reported. It is only by requiring that all AJAX requests expect this that I can easily handle all errors.

In production, the following code would probably be part of some other object or integrated into the Javascript framework in a different way, but for this demo, I’m going to break out my AJAX request pipeline into its own class:

// Create an object to handle our AJAX.
function AJAX(){
	var objSelf = this;

	// This struct will cache the current XmlHTTP requests
	// so that we can reference them if a call fails.
	this.CurrentRequests = {};
}


// This handles the JSON request. This checks to see if the current
// request is already being processed and also handles any error
// wiring that is required.
AJAX.prototype.GetJSON = function( $1, $2, $3, $4 ){
	var objSelf = this;
	var strName = $1;
	var strURL = $2;
	var objOptions = $3;
	var fnCallback = $4;

	// Check to see if there are only three arguments. If there
	// are only 3, then the first one (name of request) which is
	// optional was not passed in. Shift the other arguments
	// to the appropriate variables.
	if (arguments.length == 3){

		// Name is not being used.
		strName = null;
		strURL = $1;
		objOptions = $2;
		fnCallback = $3;

	}

	// First, we have to check to see if this request is
	// already being processed. We don't want the user to
	// try and fire off multiple requests of the same type.
	// Of course, if the name is NULL, then don't worry.
	if (!strName || !this.CurrentRequests[ strName ]){

		// Store current request.
		this.CurrentRequests[ strName ] = true;

		// Make actual AJAX request.
		$.ajax(
			{
				// Basic JSON properties.
				url: strURL,
				data: objOptions,
				dataType: "json",

				// The success call back.
				success: function( objResponse ){
					// Remove request flag.
					objSelf.CurrentRequests[ strName ] = false;

					// Pass off to success handler.
					fnCallback( objResponse );
				},

				// The error handler.
				error: function( objRequest ){
					// Remove request flag.
					objSelf.CurrentRequests[ strName ] = false;

					// Pass off to fail handler.
					objSelf.AJAXFailHandler(
						objRequest,
						fnCallback
						);
				}
			}
			);

	} else {

		// This request is currently being processed.
		alert( "Request being processed. Be patient." );

	}
}


// This will handle all AJAX failures.
AJAX.prototype.AJAXFailHandler = function( objRequest, fnCallback ){
	// Since this AJAX request failed, let's call the callback
	// but manually create a failure response.
	fnCallback(
		{
			SUCCESS: false,
			DATA: "",
			ERRORS: [ "Request failed" ]
		}
		);
}

(I’m sorry the color coding doesn’t work for my Javascript files) There’s not a whole lot going on here, but let’s walk through it. First off, one thing you can do here is make sure that only one AJAX request (of a particular type) can be processed at a time. The GetJSON() method here can take 3 or 4 arguments. If you pass in the first, optional argument — the name of the request — the GetJSON() logic will make sure that it does not launch multiple instances of the same type of AJAX request at any one time. If you pass in only the three required fields, the GetJSON() method will allow parallel AJAX requests of the same type. You will see this in the demo below — I serialize my 200 requests but allow my 404 requests to happen in parallel.

The methodology that I use leverages the $.ajax() jQuery method. I used to just use the $.getJSON() method of the jQuery library, but the $.ajax() method gives us access to the Error call back method of the AJAX request. With this method and my unified AJAX response, handling errors is actually quite easy. All AJAX errors are piped through my AJAXFailHandler() method which creates a «fail» AJAX response (sets SUCCESS flag to false) and then manually executes the AJAX callback, passing in the fail response. This way, from the AJAX response handler’s point of view, it has no idea that anything has gone wrong — it only knows that it received a response object that was either flagged as a success or a failure.

Now, let’s take a look at the demo page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>Handling AJAX Errors With jQuery</title>
	<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
	<script type="text/javascript" src="script.js"></script>
	<script type="text/javascript">

		// Initialize document.
		$(
			function(){
				var objAJAX = new AJAX();

				// Get reference to the three links.
				var j404 = $( "#error-404" );
				var jNoError = $( "#no-error" );

				// Set up 404 link.
				j404
					.attr( "href", "javascript:void(0)" )
					.click(
						function( objEvent ){
							// Make AJAX request.
							objAJAX.GetJSON(
								"does-not-exist.cfm",
								{},
								Do404RequestHandler
								);

							// Prevent default.
							objEvent.preventDefault();
							return( false );
						}
						)
				;

				// Set up no-error link.
				jNoError
					.attr( "href", "javascript:void(0)" )
					.click(
						function( objEvent ){
							// Make AJAX request.
							objAJAX.GetJSON(
								"NoErrorRequest",
								"200.cfm",
								{},
								NoErrorRequestHandler
								);

							// Prevent default.
							objEvent.preventDefault();
							return( false );
						}
						)
				;
			}
			);


		// I handle the 404 request repsonse.
		function Do404RequestHandler( objResponse ){
			// Check to see if request was successful.
			if (objResponse.SUCCESS){

				alert( "Success!" );

			} else {

				alert( "404 Error!" );
			}
		}


		// I handle the no-error request repsonse.
		function NoErrorRequestHandler( objResponse ){
			// Check to see if request was successful.
			if (objResponse.SUCCESS){

				alert( "Success!" );

			} else {

				alert( "No-Error Error!" );
			}
		}

	</script>
</head>
<body>

	<h1>
		Handling AJAX Errors With jQuery
	</h1>

	<p>
		<a id="error-404">404 Error</a> &nbsp;|&nbsp;
		<a id="no-error">Success</a>
	</p>

</body>
</html>

As you can see above, we are using jQuery to hook the links up to launch AJAX calls. Each of the two links — 404 and 200 responses — has its own response handler method. These methods, check to see if the response object was successful and just alerts the user. Notice that only the 200 style request passes in the name of the request, «NoErrorRequest»; this will ensure that the 200 style requests are serialized. The 404 style request, on the other hand, does not label its AJAX requests and therefore can make as many parallel requests as it likes.

I’m sure that I will continue to evolve the way I handle these situations over time, but so far, I have been really pleased with this methodology. It completely differentiates the two types of AJAX errors — logical vs. critical — and moves all critical error handling out of the business logic of the application.

If you are curious to see what is happening at the other end of the 200.cfm request, here is that template:

<!--- Create the response. --->
<cfset objResponse = {
	Success = true,
	Data = "Good request",
	Errors = []
	} />

<!--- Serialize the response. --->
<cfset strJSON = SerializeJSON( objResponse ) />

<!--- Get the binary response. --->
<cfset binJSON = ToBinary( ToBase64( strJSON ) ) />

<!--- Stream it back. --->
<cfheader
	name="content-length"
	value="#ArrayLen( binJSON )#"
	/>

<cfcontent
	type="text/json"
	variable="#binJSON#"
	/>

As you can see, it simply creates my unified AJAX response object and streams it back to the client.

Want to use code from this post?
Check out the license.

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!

Ошибки возникающие, при работе с Ajax

uncaught exception: permission denied to call method XMLHttpRequest.open

Эта ошибка возникает при обращении к домену, отличному от текущего.

Пути решения

  • Отказаться от использования сторонних рессурсов и перенести все необходимое на свой сервер.

решение для Internet Explorer:

Описание дано для русскоязычной версии IE7 + WinXP SP2 Rus. В других версиях/языках нужно исправить аналогичные настройки.

Свойства обозревателя > закладка «Безопасность» > зона «Надежные узлы» > кнопка «Узлы». Снять галочку «Для всех узлов этой зоны требуется проверка серверов (https:)», добавить узел seochecker. Net и нажать кнопку «Закрыть». Выбрать «Уровень безопасности для этой зоны» нажав на кнопку «Другой…» Найти параметр «Разное» > «Доступ к источникам данных за пределами домена», выбрать «Предлагать» (при открытии сайта htmlweb.ru вам нужно будет отвечать «да» на запрос безопасности) или «Включить» (дополнительных запросов не будет) и сохранить изменения.

Перейти на главную страницу и продолжить работу.

решение для Mozzila FireFox:

Создать файл User.js:

user_pref("capability.principal.codebase.htmlweb.granted", "UniversalBrowserRead");
user_pref("capability.principal.codebase.htmlweb. ID", " HTTP://htmlweb.ru");
user_pref("capability.principal.codebase.htmlweb.subjectName", "htmlweb");

user_pref("capability.principal.codebase.htmlwebwww.granted", "UniversalBrowserRead");
user_pref("capability.principal.codebase.htmlwebwww.id", "http://htmlweb.ru");
user_pref("capability.principal.codebase.htmlwebwww.subjectName", "htmlweb");

user_pref("signed.applets.codebase_principal_support", true);

Вместо htmlweb.ru подставьте свой сайт. Поместите его в директорию вашего профиля Firefox. Обычно путь к этой директории имеет вид:

 C++:Documents and Settingsлогин_пользователя
	Application Data MozillaFirefoxProfiles
		случайные_символы.default

Файл не переименовывать, оставить название user.js. Перезапустить Firefox.

Данная операция добавит сайт указанный вами домен в «доверенные», которым разрешено получать данные с источников за пределами домена.

Кроме этого, выключите Firebag для этого сайта!

Для проверки из JavaScript доступности получения информации из-за пределов домена я использую следующий код:

if(!window.ActiveXObject)
try {
if (netscape.security.PrivilegeManager.enablePrivilege) {
    netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
    }
} catch (e) {alert('Настройка безопасности браузера не позволяет обращаться к другим сайтам!n'+e); return false;}

Обработка ошибки метода open объекта ajax:

try {
  ajaxObj.open ('GET',  URL); }
catch (e) {if(window.ActiveXObject)alert('Разрешите получать информацию с других сайтов!n'+e);
       else alert('Выключите Firebag для этого сайта,nиначе Вы не сможете увидеть весь анализ на одной странице!n'+e);
      }

This function basically generates unique random API key’s and in case if it doesn’t then pop-up dialog box with error message appears

In View Page:

<div class="form-group required">
    <label class="col-sm-2 control-label" for="input-storename"><?php echo $entry_storename; ?></label>
    <div class="col-sm-6">
        <input type="text" class="apivalue"  id="api_text" readonly name="API" value="<?php echo strtoupper(substr(md5(rand().microtime()), 0, 12)); ?>" class="form-control" />                                                                    
        <button type="button" class="changeKey1" value="Refresh">Re-Generate</button>
    </div>
</div>

<script>
$(document).ready(function(){
    $('.changeKey1').click(function(){
          debugger;
        $.ajax({
                url  :"index.php?route=account/apiaccess/regenerate",
                type :'POST',
                dataType: "json",
                async:false,
                contentType: "application/json; charset=utf-8",
                success: function(data){
                  var result =  data.sync_id.toUpperCase();
                        if(result){
                          $('#api_text').val(result);
                        }
                  debugger;
                  },
                error: function(xhr, ajaxOptions, thrownError) {
                  alert(thrownError + "rn" + xhr.statusText + "rn" + xhr.responseText);
                }

        });
    });
  });
</script>

From Controller:

public function regenerate(){
    $json = array();
    $api_key = substr(md5(rand(0,100).microtime()), 0, 12);
    $json['sync_id'] = $api_key; 
    $json['message'] = 'Successfully API Generated';
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}

The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:

Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

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 cross-domain JSONP requests.

This function basically generates unique random API key’s and in case if it doesn’t then pop-up dialog box with error message appears

In View Page:

<div class="form-group required">
    <label class="col-sm-2 control-label" for="input-storename"><?php echo $entry_storename; ?></label>
    <div class="col-sm-6">
        <input type="text" class="apivalue"  id="api_text" readonly name="API" value="<?php echo strtoupper(substr(md5(rand().microtime()), 0, 12)); ?>" class="form-control" />                                                                    
        <button type="button" class="changeKey1" value="Refresh">Re-Generate</button>
    </div>
</div>

<script>
$(document).ready(function(){
    $('.changeKey1').click(function(){
          debugger;
        $.ajax({
                url  :"index.php?route=account/apiaccess/regenerate",
                type :'POST',
                dataType: "json",
                async:false,
                contentType: "application/json; charset=utf-8",
                success: function(data){
                  var result =  data.sync_id.toUpperCase();
                        if(result){
                          $('#api_text').val(result);
                        }
                  debugger;
                  },
                error: function(xhr, ajaxOptions, thrownError) {
                  alert(thrownError + "rn" + xhr.statusText + "rn" + xhr.responseText);
                }

        });
    });
  });
</script>

From Controller:

public function regenerate(){
    $json = array();
    $api_key = substr(md5(rand(0,100).microtime()), 0, 12);
    $json['sync_id'] = $api_key; 
    $json['message'] = 'Successfully API Generated';
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}

The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:

Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

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 cross-domain JSONP requests.

I am sending an error response to my jQuery.
However, I can not get the response text (in the example below this would be Gone to the beach)

The only thing jQuery says is ‘error’.

See this example for details:

php

<?
    header('HTTP/1.1 500 Internal Server Error');
    print "Gone to the beach"
?>

jQuery

$.ajax({
    type:     "post",
    data:     {id: 0},
    cache:    false,
    url:      "doIt.php",
    dataType: "text",
    error: function (request, error) {
        console.log(arguments);
        alert(" Can't do because: " + error);
    },
    success: function () {
        alert(" Done ! ");
    }
});

Now my result ist:

log:

 [XMLHttpRequest readyState=4 status=500, "error", undefined]

alert:

Can’t do because: error

Any ideas?

robsch's user avatar

robsch

9,2489 gold badges61 silver badges100 bronze badges

asked Oct 28, 2009 at 12:40

jantimon's user avatar

2

Try:

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}

Matt's user avatar

Matt

74.1k26 gold badges153 silver badges180 bronze badges

answered Oct 28, 2009 at 12:46

Alex Bagnolini's user avatar

Alex BagnoliniAlex Bagnolini

21.9k3 gold badges41 silver badges41 bronze badges

9

For me, this simply works:

error: function(xhr, status, error) {
  alert(xhr.responseText);
}

answered Aug 15, 2013 at 18:03

HaoQi Li's user avatar

HaoQi LiHaoQi Li

11.9k14 gold badges58 silver badges77 bronze badges

Look at the responseText property of the request parameter.

Dave Jarvis's user avatar

Dave Jarvis

30.3k40 gold badges178 silver badges315 bronze badges

answered Oct 28, 2009 at 12:43

tvanfosson's user avatar

tvanfossontvanfosson

523k99 gold badges697 silver badges794 bronze badges

5

As ultimately suggested by this other answer and it’s comments on this page:

error: function(xhr, status, error) {
  var err = JSON.parse(xhr.responseText);
  alert(err.Message);
}

Community's user avatar

answered May 5, 2016 at 13:00

Brad Parks's user avatar

Brad ParksBrad Parks

66k64 gold badges256 silver badges332 bronze badges

The best simple approach :

error: function (xhr) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}

answered Apr 19, 2018 at 18:07

Mazen Embaby's user avatar

Mazen EmbabyMazen Embaby

1,24311 silver badges18 bronze badges

This is what worked for me

    function showErrorMessage(xhr, status, error) {
        if (xhr.responseText != "") {

            var jsonResponseText = $.parseJSON(xhr.responseText);
            var jsonResponseStatus = '';
            var message = '';
            $.each(jsonResponseText, function(name, val) {
                if (name == "ResponseStatus") {
                    jsonResponseStatus = $.parseJSON(JSON.stringify(val));
                     $.each(jsonResponseStatus, function(name2, val2) {
                         if (name2 == "Message") {
                             message = val2;
                         }
                     });
                }
            });

            alert(message);
        }
    }

answered Jan 31, 2014 at 2:01

user3255682's user avatar

1

If you want to get Syntax Error with line number, use this

error: function(xhr, status, error) {
  alert(error);
}

answered Oct 9, 2015 at 14:34

Karthikeyan P's user avatar

Karthikeyan PKarthikeyan P

1,1961 gold badge19 silver badges23 bronze badges

2

you can try it too:

$(document).ajaxError(
    function (event, jqXHR, ajaxSettings, thrownError) {
        alert('[event:' + event + '], [jqXHR:' + jqXHR + '], [ajaxSettings:' + ajaxSettings + '], [thrownError:' + thrownError + '])');
    });

answered Nov 24, 2011 at 23:17

85tisgirjetuji8's user avatar

0

This will allow you to see the whole response not just the «responseText» value

error: function(xhr, status, error) {
    var acc = []
    $.each(xhr, function(index, value) {
        acc.push(index + ': ' + value);
    });
    alert(JSON.stringify(acc));
}

answered Mar 15, 2016 at 11:36

Kareem's user avatar

KareemKareem

5,02043 silver badges38 bronze badges

I used this, and it worked perfectly.

error: function(xhr, status, error){
     alertify.error(JSON.parse(xhr.responseText).error);
}

Dharman's user avatar

Dharman

30.5k22 gold badges84 silver badges133 bronze badges

answered Aug 15, 2019 at 17:56

Juan Silupú Maza's user avatar

3

Try this to have complete error detail in console.

error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log("Error Thrown: " + errorThrown);
                    console.log("Text Status: " + textStatus);
                    console.log("XMLHttpRequest: " + XMLHttpRequest);
                    console.warn(XMLHttpRequest.responseText)
               }

Carn's user avatar

answered Jul 16, 2022 at 20:50

Ateeq Rafeeq's user avatar

If you’re not having a network error, and wanting to surface an error from the backend, for exmple insufficient privileges, server your response with a 200 and an error message. Then in your success handler check data.status == ‘error’

answered Oct 8, 2012 at 6:21

chovy's user avatar

chovychovy

71.5k51 gold badges222 silver badges284 bronze badges

6

err.responseText contain HTML tags you can get error message from these tags easily…
For example:

$(err.responseText)
// k.fn.init(12) [text, title, text, meta, text, style, text, span, text, font, text, //comment]

$.ajax({
    async: bAsync,
    type: 'POST',
    url: pUrl,
    contentType: 'application/json; charset=utf-8;',
    dataType: 'json',
    data: pData,
    success: fn,
    error: function(err) {
        alert( $($(err.responseText)[1]).text() )
        debugger;
    }
});

Tyler2P's user avatar

Tyler2P

2,30425 gold badges22 silver badges31 bronze badges

answered Dec 21, 2021 at 13:22

MUHAMMAD NOMAN KHALID's user avatar

1

Время на прочтение
13 мин

Количество просмотров 61K

Всем привет в новой записи мы с вами разберём основные функции для Ajax запросов, которые позволяют передавать информацию с сайта в PHP скрипт без перезагрузки страницы.

Для работы Ajax запросов вам нужно подключить jQuery к вашему проекту. Ссылку на jQuery вы можете найти здесь.

Данный взяты с моего сайта Prog-Time.

Стандартная отправка данных через Ajax.

$.ajax({
    url: '/index.php',         /* Куда отправить запрос */
    method: 'get',             /* Метод запроса (post или get) */
    dataType: 'html',          /* Тип данных в ответе (xml, json, script, html). */
    data: {text: 'Текст'},     /* Данные передаваемые в массиве */
    success: function(data){   /* функция которая будет выполнена после успешного запроса.  */
	     alert(data); /* В переменной data содержится ответ от index.php. */
    }
});

Отправка POST запроса через Ajax

Для отправки POST запроса используем подобный код, меняем только параметр method

$.ajax({
    url: '/index.php',
    method: 'post',
    dataType: 'html',
    data: {text: 'Текст'},
    success: function(data){
	alert(data);
    }
});

Отправка JSON данных через Ajax

Для отправки JSON данный через AJAX можно использовать только методом GET.

$.ajax({
    url: '/json.php',
    method: 'get',
    dataType: 'json',
    success: function(data){
			alert(data.text);    /* выведет "Текст" */
			alert(data.error);   /* выведет "Ошибка" */
    }
});

Запланировать выполнение JS скрипта

После выполнения данного запроса, скрипт указанный в параметре url сразу будет выполнен.

$.ajax({
    method: 'get',
    url: '/script.js',
    dataType: "script"
});

Сокращённые виды функций для Ajax запросов

$.post('/index.php', {text: 'Текст'}, function(data){
    alert(data);
});
$.get('/index.php', {text: 'Текст'}, function(data){
    alert(data);
});
$.getJSON('/json.php', function(data) {
    alert(data.text);
    alert(data.error);
});

Сокращённая версия запроса на выполнение JS скрипта

$.getScript('/script.js');

Обработка ошибок связанных с AJAX запросом

$.ajax({
    url: '/index.php',
    method: 'get',
    dataType: 'json',
    success: function(data){
	console.dir(data);
    },
    error: function (jqXHR, exception) {
	if (jqXHR.status === 0) {
		alert('Not connect. Verify Network.');
	} else if (jqXHR.status == 404) {
		alert('Requested page not found (404).');
	} else if (jqXHR.status == 500) {
		alert('Internal Server Error (500).');
	} else if (exception === 'parsererror') {
		alert('Requested JSON parse failed.');
	} else if (exception === 'timeout') {
		alert('Time out error.');
	} else if (exception === 'abort') {
		alert('Ajax request aborted.');
	} else {
		alert('Uncaught Error. ' + jqXHR.responseText);
	}
    }
});

7 Основные параметры для работы с AJAX функциями

Справочные данные взяты с сайта – https://basicweb.ru/jquery/jquery_method_ajax.php

Все параметры для отправки AJAX запросов

  • async (по умолчанию: true).Тип: Boolean.По умолчанию, все запросы отправляются асинхронно и не задерживают работу других JS скриптов (это значение true), для того чтобы ждать пока выполниться Ajax запрос – поставьте значение false.Обратите внимание, что кроссдоменные запросы и элемент, параметр dataType которого имеет значение “jsonp” не поддерживают запросы в синхронном режиме. Учтите, что используя синхронные запросы вы можете временно заблокировать браузер отключив какие-либо действия пока запрос будет активен.

  • beforeSendФункция обратного вызова, которая будет вызвана перед осуществлением AJAX запроса. Функция позволяет изменить объект jqXHR (в jQuery 1.4.х объект XMLHTTPRequest) до его отправки. Объект jqXHR это надстройка расширяющая объект XMLHttpRequest, объект содержит множество свойств и методов, которые позволяет получить более полную информацию об ответе сервера, а так же объект содержит Promise методы. Если функция beforeSend возвращает false, то AJAX запрос будет отменен. Начиная с версии jQuery 1.5 функция beforeSend будет вызываться независимо от типа запроса.

  • cache (по умолчанию: true, для dataType “script” и “jsonp” false).Тип: Boolean.Если задано значение false, то это заставит запрашиваемые страницы не кэшироваться браузером. Обратите внимание, что значение false будет правильно работать только с HEAD и GET запросами.

  • complete.Тип: FunctionjqXHR jqXHRString textStatus ).Функция, которая вызывается, когда запрос заканчивается (функция выполняется после AJAX событий “success” или “error”). В функцию передаются два параметра: jqXHR (в jQuery 1.4.х объект XMLHTTPRequest) и строка соответствующая статусу запроса (“success”“notmodified”“nocontent”“error”“timeout”“abort”, или “parsererror”). Начиная с версии jQuery 1.5 параметр complete может принимать массив из функций, которые будут вызываться по очереди.

  • contents.Тип: PlainObject.Объект состоящий из пар строка/регулярное выражение, определяющих, как jQuery будет обрабатывать (парсить) ответ в зависимости от типа содержимого. Добавлен в версии jQuery 1.5.

  • contentType (по умолчанию: “application/x-www-form-urlencoded; charset=UTF-8”).Тип: Boolean, или String.Определяет тип содержимого, которое указывается в запросе при передаче данных на сервер. С версии с jQuery 1.6 допускается указать значение false, в этом случае jQuery не передает в заголовке поле Content-Type совсем.

  • context.Тип: PlainObject.При выполнении AJAX функций обратного вызова контекстом их выполнения является объект window. Параметр context позволяет настроить контекст исполнения функции таким образом, что $( this ) будет ссылаться на определенный DOM элемент, или объект.

$.ajax({
    url: "test.html", // адрес, на который будет отправлен запрос
    context: $( ".myClass" ), // новый контекст исполнения функции
    success: function(){ // если запрос успешен вызываем функцию
        $( this ).html( "Всё ок" ); // добавляем текст в элемент с классом .myClass
    }
});
  • crossDomain (по умолчанию: false для запросов внутри того же домена, true для кроссдоменных запросов).Тип: Boolean.Если вы хотите сделать кроссдоменный запрос находясь на том же домене (например jsonp-запрос), то установите этот параметр в true. Это позволит, к примеру, сделать перенаправление запроса на другой домен с вашего сервера. Добавлен в версии jQuery 1.5.

  • data.Тип: PlainObject, или String, или Array.Данные, которые будут отправлены на сервер. Если они не является строкой, то преобразуются в строку запроса. Для GET запросов строка будет добавлена к URL. Для того, чтобы предотвратить автоматическую обработку вы можете воспользоваться параметром processData со значением false. Если данные передаются в составе объекта, то он должен состоять из пар ключ/значение. Если значение является массивом, то jQuery сериализует несколько значений с одним и тем же ключом (в зависимости от значения параметра traditional, который позволяет задействовать традиционный тип сериализации основанный на методе $.param).

  • dataFilter.Тип: FunctionString dataString type ) => Anything.Функция вызывается после успешного выполнения AJAX запроса и позволяет обработать “сырые” данные, полученные из ответа сервера. Возврат данных должен происходить сразу после их обработки. Функция принимает два аргумента: data – данные полученные от сервера в виде строки и type – тип этих данных (значение параметра dataType).

  • dataType (по умолчанию: xmljsonscript, или html ).Тип: String.Определяет тип данных, который вы ожидаете получить от сервера. Если тип данных не указан, то jQuery будет пытаться определить его на основе типа MIME из ответа (XML тип MIME приведет к получению XML, с версии jQuery 1.4 json будет давать объект JavaScriptscript будет выполнять скрипт, а все остальное будет возвращено в виде строки).Основные типы (результат передается в качестве первого аргумента в функцию обратного вызова success):

    • “xml” – возвращает XML документ, который может быть обработан с помощью jQuery.

    • “html” – возвращает HTML как обычный текст, теги <script> будут обработаны и выполнены после вставки в объектную модель документа (DOM).

    • “script” – расценивает ответ как JavaScript и возвращает его как обычный текст. Отключает кэширование с помощью добавления параметра к строке запроса _=[TIMESTAMP], даже если парамета cache имеет значение true. Это превратит метод POST в GET для кроссдоменных запросов.

    • “json” – расценивает ответ как JSON и возвращает объект JavaScript. Кроссдоменные “json” запросы преобразуются в “jsonp”, если в параметрах запроса не указано jsonpfalse. Данные JSON парсятся в строгом порядке и должны соответствовать общепринятому формату, любой некорректный JSON отвергается и выдается ошибка. С версии jQuery 1.9, пустой ответ не принимается, сервер должен вернуть в качестве ответа NULL, или {}.

    • “jsonp” – загружает данные в формате JSON, используя при этом формат загрузки JSONP. Добавляет дополнительный параметр “?callback=?” в конец URL адреса для указания имени функции обработчика. Отключает кэширование путем добавления параметра _=[TIMESTAMP] к URL адресу,даже если парамета cache имеет значение true.

    • “text” – обычная текстовая строка.

    • несколько значений – значения разделяются пробелом. Начиная с версии 1.5, jQuery может преобразовать тип данных, который получен в Content-Type заголовка, в тип данных, который вам требуется. Например, если вы хотите, чтобы текстовый ответ был расценен как XML, используйте “text XML” для этого типа данных. Вы также можете сделать JSONP запрос, получить его в виде текста и интерпретировать его в формате XML: “jsonp text XML”. Следующая строка позволит сделать тоже самое: “jsonp XML”, jQuery будет пытаться конвертировать из JSONP в XML, после неудачной попытки попытается преобразовать JSONP в текст, а затем из текста уже в XML.

  • error.Тип: FunctionjqXHR jqXHRString textStatusString errorThrown ).Функция обратного вызова, которая вызывается если AJAX запрос не был выполнен. Функция получает три аргумента:

    • jqXHR – объект jqXHR (в jQuery 1.4.х, объект XMLHttpRequest).

    • textStatus – строка, описывающую тип ошибки, которая произошла. Возможные значения (кроме null) не “timeout”“error”“abort” и “parsererror”.

    • errorThrown – дополнительный объект исключения, если произошло. При возникновении ошибки HTTP аргумент получает текстовую часть состояния, например, “Not Found”, или “Internal Server Error”.Начиная с версии jQuery 1.5 допускается передавать в качестве значения параметра массив функций, при этом каждая функция будет вызвана в свою очедерь. Обратите внимание, что этот обработчик не вызывается для кроссдоменных скриптов и запросов JSONP.

  • global (по умолчанию: true).Тип: Boolean.Логический параметр, который определяет допускается ли вызвать глобальные обработчики событий AJAX для этого запроса. Значением по умолчанию является true. Если Вам необходимо предотвратить вызов глобальных обработчиков событий, таких как .ajaxStart(), или .ajaxStop(), то используйте значение false.

  • headers (по умолчанию: { }).Тип: PlainObject.Объект, который содержит пары ключ/значение дополнительных заголовков запроса, предназначенные для отправки вместе с запросом с использованием объекта XMLHttpRequest. Обращаю Ваше внимание, что заголовок X-Requested-With: XMLHttpRequest добавляется всегда, но значение XMLHttpRequest по умоланию допускается изменить с использованием этого параметра. Значения headers также могут быть переопределены параметром beforeSend. Добавлен в версии jQuery 1.5.

  • ifModified (по умолчанию: false).Тип: Boolean.По умолчанию значение false, игнорирует поля заголовка HTTP запроса, а при значении true AJAX запрос переводится в статус успешно (success), только в том случае, если ответ от сервера изменился с момента последнего запроса. Проверка производится путем проверки поля заголовка Last-Modified. Начиная с версии jQuery 1.4, помимо заголовка Last-Modified производится проверка и “etag” (entity tag) – это закрытый идентификатор, присвоенный веб-сервером на определенную версию ресурса, найденного на URL. Если содержание ресурса для этого адреса меняется на новое, назначается и новый etag.

  • isLocal (по умолчанию: зависит от текущего местоположения).Тип: Boolean.Используйте значение true для определения текущего окружения как “локального” (например, file:///url), даже если jQuery не распознает его таким по умоланию. Следующие протоколы в настоящее время признаются как локальные: file*-extension и widget. Если Вам необходимо изменить параметр isLocal, то рекомендуется сделать это один раз при помощи функции $.ajaxSetup(). Добавлен в версии jQuery 1.5.1.

  • jsonpТип: Boolean, или String.Переопределяет имя функции обратного вызова в JSONP запросе. Это значение будет использоваться вместо “callback“ (“http://domain.ru/test.php?callback=?”) в составе части строки запроса в URL адресе. Например, значение {jsonp: “onLoad} передастся на сервер в виде следующей строки запроса “http://domain/test.php?onLoad=?”.Начиная с версии jQuery 1.5 при установке значения параметра jsonp в значение false предотвращает добавление строки “?callback” к URL адресу, или попытки использовать “=?” для преобразования ответа. В этом случае Вы дополнительно должны указать значение параметра jsonpCallback. По соображениям безопасности, если Вы не доверяете цели ваших AJAX запросов, то рекомендуется установить значение параметра jsonp в значение false.

{
  jsonp: false,
  jsonpCallback: "callbackName"
}
  • jsonpCallback.Тип: String, или Function.Задает имя функции обратного вызова для JSONP запроса. Это значение будет использоваться вместо случайного имени, которое автоматически генерируется и присваивается библиотекой jQuery. Рекомендуется, чтобы jQuery самостоятелно генерировало уникальное имя, это позволит легче управлять запросами и обрабатывать возможные ошибки. В некоторых случаях установка собственного имени функции позволит улучшить браузерное кеширование GET запросов.Начиная с версии jQuery 1.5, вы можете в качестве значения параметра jsonpCallback указать функцию. В этом случае, в значение параметра jsonpCallback должно быть установлено возвращаемое значение этой функцией.

  • method (по умолчанию: “GET”).Тип: String.Метод HTTP, используемый для запроса (например, “POST”“GET”“PUT”). Добавлен в версии jQuery 1.9.0.

  • mimeType.Тип: String.MIME тип, который переопределяет MIME тип, указанынй в объекте XHR по умолчанию. Добавлен в версии jQuery 1.5.1.

  • password.Тип: String.Пароль, который будет использован с XMLHttpRequest в ответе на запрос проверки подлинности доступа HTTP.

  • processData (по умолчанию: true).Тип: Boolean.По умолчанию данные, передаваемые в параметр data в качестве объекта будут обработаны и преобразованы в строку запроса, подходящую для типа данных по умолчанию “application/x-www-form-urlencoded”. Если Вам необходимо отправить DOMDocument, или другие не обработанные данные, то установите значение этого параметра в false.

  • scriptCharset.Тип: String.Устанавливает атрибут charset (кодировка символов) на HTML тег <script>, используемый в запросе. Используется, когда кодировка на странице отличается от кодировки удаленного скрипта. Обратите внимание, что параметр scriptCharset применяется только в кроссдоменных запросах с параметром type со значением “GET” (по умолчанию) и параметром dataType со значением “jsonp”, или “script”.

  • statusCode (по умолчанию: { }).Тип: PlainObject.Объект числовых кодов HTTP и функции, которые будут вызываться, когда код ответа сервера имеет соотвествующее значение (определенный код HTTP). Например, следующая функция будет вызвана, если от сервера получен код ответа 404, или “Not found” (стандартный код ответа HTTP о том, что клиент был в состоянии общаться с сервером, но сервер не может найти данные согласно запросу.)

$.ajax({
  statusCode: { 
    404: function(){ // выполнить функцию если код ответа HTTP 404
      alert( "страница не найдена" );
    },
    403: function(){ // выполнить функцию если код ответа HTTP 403
      alert( "доступ запрещен" );
    } 
  }
});
  • success.Тип: FunctionAnything dataString textStatusjqXHR jqXHR ).Функция обратного вызова, которая вызывается если AJAX запрос выполнится успешно. Функции передаются три аргумента:

    • data – данные возвращенные с сервера. Данные форматируюся в соответствии с параметрами dataType, или dataFilter, если они указаны

    • textStatus – строка описывающая статус запроса.

    • jqXHR – объект jqXHR (до версии jQuery 1.4.x объект XMLHttpRequest).Начиная с версии jQuery 1.5 допускается передавать в качестве значения параметра массив функций, при этом каждая функция будет вызвана в свою очедерь.

  • timeout.Тип: Number.Устанавливает в миллисекундах таймаут для запроса. Значение 0 означает, что таймаут не установлен. Обращаю Ваше внимание, что этот параметр переопределяет значение таймаута, установленного с помощью функции $.ajaxSetup(). Таймаут ожидания начинается в момент вызова метода $.ajax().

  • traditional.Тип: Boolean.Если вы планируете использовать традиционные параметры сериализации (подходит для использования в строке URL запроса или запроса AJAX), то установите значение этого параметра в true.

  • type (по умолчанию: “GET”).Тип: String.Псевдоним (алиас) для параметра method. Вы должны использовать type, если вы используете версии jQuery до 1.9.0.

  • url (по умолчанию: текущая страница).Тип: String.Строка, содержащая URL адрес, на который отправляется запрос.

  • username.Тип: String.Имя пользователя, которое будет использовано с XMLHttpRequest в ответе на запрос проверки подлинности доступа HTTP.

  • xhr (по умолчанию: ActiveXObject, когда доступен (Internet Explorer), в других случаях XMLHttpRequest.Тип: Function().Обратный вызов для создания объекта XMLHttpRequest. С помощью этого параметра Вы можете переопределить объект XMLHttpRequest, чтобы обеспечить свою собственную реализацию.

  • xhrFields.Тип: PlainObject.Объект, содержащий пары имя_поля: значение_поля, которые будут установлены на объект XHR. Например, вы можете определить, должны ли создаваться кроссдоменные запросы с использованием таких идентификационных данных как cookie, авторизационные заголовки или TLS сертификаты

$.ajax({
  url: "cross_domain_url", // адрес, на который будет отправлен запрос
  xhrFields: { 
    withCredentials: true // поддерживается в jQuery 1.5.1 +
  }
});

Форма с отправкой файлов методом AJAX

Создаём форму с 2 текстовыми полями name и phone, и одним полем для передачи файла (fileImage)

HTML

<form id="feedBack" method="post" onsubmit="return false">
    <input type="text" name="name" placeholder="Имя">
    <input type="tel" name="phone" placeholder="Телефон">
&lt;input type="file" name="fileImage" accept=".jpg, .jpeg, .png" multiple="multiple"&gt;
&lt;input type="submit" value="Отправить"&gt;

</form>

JQUERY

/* запускаем скрипт после полной загрузки документа /
$("document").ready(function() {
  / вешаем событие на ранее созданную форму /
  $("#feedBack").on("submit", function() {
    / создаём объект с данными из полей /
    let formData = new FormData(feedBack)
    / добавляем дополнительные данные для отправки */
    formData.append("url_query", "prog-time");
        /* записываем в переменную данные картинок из формы */
    let allfiles = $(this).find('input[name="fileImage"]');

        /* пробегаем покартинкам и записываем их в массив для отправки */
    for(var i = 0; i &lt; allfiles[0].files.length; i++){
        formData.append("file_"+i, allfiles[0].files[i]); 
    }

        /* отправляем AJAX запрос */
    $.ajax({
        type: "POST",
        url: '/query.php',
        contentType: false,
        processData: false,
        data: formData,
        success: function(data){
      console.log(data)
        },
    });

  })

})

11 PHP

/* ... прописываем необходимые проверки и обработки данных */
/* сохраняем картинки на сервере */
	foreach(image["name"], $image["tmp_name"]);
}

На этом всё!
Прокачивайте свои навыки на нашем канале.

In this article I will explain how to handle errors and exceptions in jQuery AJAX calls and show (display) Custom Exception messages using jQuery Dialog.

There are two types of Exceptions which is caught by jQuery

1. When exception object is in the form of JSON object.

2. When exception object is in the form of plain text or HTML.

I will explain both the types with detailed explanation and also how to display the exception error details in both the cases.

WebMethod for testing both types

In order to test both the cases I have created the following WebMethod which simply tries to convert the received string value to integer.

[System.Web.Services.WebMethod]

public static void ValidateNumber(string number)

{

    int no = Convert.ToInt32(number);

}

1. When exception object is in the form of JSON object

In the following HTML Markup, I have created a simple form with a TextBox and a Button which prompts user to enter a Numeric value.

The value entered is passed to the WebMethod using a jQuery AJAX call where it is converts string value to integer.

If it is a valid number then an alert message is displayed inside the jQuery AJAX Success event handler and if an exception occurs in the WebMethod, the thrown exception is caught inside the jQuery AJAX Error event handler and which makes a call to the OnError JavaScript function which processes and displays the exception details.

<html xmlns=»http://www.w3.org/1999/xhtml»>

<head runat=»server»>

    <title></title>

    <style type=»text/css»>

        body { font-family: Arial; font-size: 10pt; }

        #dialog { height: 600px; overflow: auto; font-size: 10pt !important; font-weight: normal !important; background-color: #FFFFC1; margin: 10px; border: 1px solid #ff6a00; }

        #dialog div { margin-bottom: 15px; }

    </style>

</head>

<body>

    <form id=»form1″ runat=»server»>

        <u>1: When exception object is in the form of JSON object</u>

        <br/>

        <br/>

        Enter Number:

        <input id=»txtNumber1″ type=»text»/>

        <input id=»btnValidate1″ type=»button» value=»Validate»/>      

        <div id=»dialog» styledisplay: none»></div>

        <script type=»text/javascript» src=»http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js»></script>

        <script src=»http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js» type=»text/javascript»></script>

        <link href=»http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css»

            rel=»stylesheet» type=»text/css»/>

        <script type=»text/javascript»>

            $(function () {

                $(«#btnValidate1»).click(function () {

                    var number = $(«#txtNumber1»).val();

                    $.ajax({

                        type: «POST»,

                        url: » Default.aspx/ValidateNumber»,

                        data: ‘{number: «‘ + number + ‘»}’,

                        contentType: «application/json; charset=utf-8»,

                        dataType: «json»,

                        success: function (r) {

                            alert(«Valid number.»);

                        },

                        error: OnError

                    });

                });

            });

            function OnError(xhr, errorType, exception) {

                var responseText;

                $(«#dialog»).html(«»);

                try {

                    responseText = jQuery.parseJSON(xhr.responseText);

                    $(«#dialog»).append(«<div><b>» + errorType + » « + exception + «</b></div>»);

                    $(«#dialog»).append(«<div><u>Exception</u>:<br /><br />» + responseText.ExceptionType + «</div>»);

                    $(«#dialog»).append(«<div><u>StackTrace</u>:<br /><br />» + responseText.StackTrace + «</div>»);

                    $(«#dialog»).append(«<div><u>Message</u>:<br /><br />» + responseText.Message + «</div>»);

                } catch (e) {

                    responseText = xhr.responseText;

                    $(«#dialog»).html(responseText);

                }

                $(«#dialog»).dialog({

                    title: «jQuery Exception Details»,

                    width: 700,

                    buttons: {

                        Close: function () {

                            $(this).dialog(‘close’);

                        }

                    }

                });

            }

        </script>

    </form>

</body>

</html>

Catching, Handling and displaying Exceptions and Errors when using jQuery AJAX and WebMethod in ASP.Net

Catching, Handling and displaying Exceptions and Errors when using jQuery AJAX and WebMethod in ASP.Net

2. When exception object is in the form of HTML or plain text

The second case is similar to the first one. In order to receive a Non-JSON response I have just set incorrect WebMethod name in the jQuery AJAX so that it generates an error.

<html xmlns=»http://www.w3.org/1999/xhtml»>

<head runat=»server»>

    <title></title>

    <style type=»text/css»>

        body { font-family: Arial; font-size: 10pt; }

        #dialog { height: 600px; overflow: auto; font-size: 10pt! important; font-weight: normal !important; background-color: #FFFFC1; margin: 10px; border: 1px solid #ff6a00; }

        #dialog div { margin-bottom: 15px; }

    </style>

</head>

<body>

    <form id=»form1″ runat=»server»>

        <u>2: When exception object is in the form of HTML or plain text</u>

        <br/>

        <br/>

        Enter Number:

        <inputi d=»txtNumber2″ type=»text»/>

        <input id=»btnValidate2″ type=»button» value=»Validate»/>

        <div id=»dialog» styledisplay: none»></div>

        <script type=»text/javascript» src=»http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js»></script>

        <script src=»http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js» type=»text/javascript»></script>

        <link href=»http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css»

            rel=»stylesheet» type=»text/css»/>

        <script type=»text/javascript»>

            $(function () {

                $(«#btnValidate2»).click(function () {

                    var number = $(«#txtNumber2»).val();

                    $.ajax({

                        type: «POST»,

                        url: «Default.aspx/UnknownMethod»,

                        data: ‘{number: «‘ + number + ‘»}’,

                        contentType: «application/json; charset=utf-8»,

                        dataType: «json»,

                        success: function (r) {

                            alert(«Valid number.»);

                        },

                        error: OnError

                    });

                });

            });

            function OnError(xhr, errorType, exception) {

                var responseText;

                $(«#dialog»).html(«»);

                try {

                    responseText = jQuery.parseJSON(xhr.responseText);

                    $(«#dialog»).append(«<div><b>» + errorType + » « + exception + «</b></div>»);

                    $(«#dialog»).append(«<div><u>Exception</u>:<br /><br />» + responseText.ExceptionType + «</div>»);

                    $(«#dialog»).append(«<div><u>StackTrace</u>:<br /><br />» + responseText.StackTrace + «</div>»);

                    $(«#dialog»).append(«<div><u>Message</u>:<br /><br />» + responseText.Message + «</div>»);

                } catch (e) {

                    responseText = xhr.responseText;

                    $(«#dialog»).html(responseText);

                }

                $(«#dialog»).dialog({

                    title: «jQuery Exception Details»,

                    width: 700,

                    buttons: {

                        Close: function () {

                            $(this).dialog(‘close’);

                        }

                    }

                });

            }

        </script>

    </form>

</body>

</html>

Catching, Handling and displaying Exceptions and Errors when using jQuery AJAX and WebMethod in ASP.Net

Catching, Handling and displaying Exceptions and Errors when using jQuery AJAX and WebMethod in ASP.Net

Parsing the received Exception response using jQuery

Here I am explaining the details of the OnError JavaScript function which is called by the Error event handler in both the above case.

This function accepts the following three parameters

xhr – It is the error response object.

errorType – It describes the type of error.

exception – It contains the title of the exception occurred.

Inside this function, I have placed a TRY CATCH block and within the TRY block, the Exception received is parsed to a JSON object and then the details of the exception are displayed using jQuery Dialog Modal Popup.

If an error occurs during the process of parsing the JSON string, it means it is a Non-JSON response i.e. HTML or plain text and then it is handled inside the CATCH block where I am displaying the exception directly without any processing.

function OnError(xhr, errorType, exception) {

    var responseText;

    $(«#dialog»).html(«»);

    try {

        responseText = jQuery.parseJSON(xhr.responseText);

        $(«#dialog»).append(«<div><b>» + errorType + » « + exception + «</b></div>»);

        $(«#dialog»).append(«<div><u>Exception</u>:<br /><br />» + responseText.ExceptionType + «</div>»);

        $(«#dialog»).append(«<div><u>StackTrace</u>:<br /><br />» + responseText.StackTrace + «</div>»);

        $(«#dialog»).append(«<div><u>Message</u>:<br /><br />» + responseText.Message + «</div>»);

    } catch (e) {

        responseText = xhr.responseText;

        $(«#dialog»).html(responseText);

    }

    $(«#dialog»).dialog({

        title: «jQuery Exception Details»,

        width: 700,

        buttons: {

            Close: function () {

                $(this).dialog(‘close’);

            }

        }

    });

}

Demo

Downloads

  • Ошибка airmatic visit workshop w220
  • Ошибка airf на бобкете
  • Ошибка airbag пежо 408
  • Ошибка airbag пежо 407
  • Ошибка airbag пежо 308