Javascript-форум (https://javascript.ru/forum/)
-   ExtJS (https://javascript.ru/forum/extjs/)
-   -   "success" и "failure" приём данных с сервера ??? (https://javascript.ru/forum/extjs/28532-success-i-failure-prijom-dannykh-s-servera.html)

potkin 23.05.2012 17:30

"success" и "failure" приём данных с сервера ???
 
Вопрос в передаче ошибки с сервера

Есть Панель на ней текстовые поля и кнопочка Сохранить, код:
var PanelData = new Ext.FormPanel({
 url: 'Handlers/ХХХ.ashx?pid=' + pid + ...,
 defaultType: 'textfield',
 ...
 buttons: [{
  text: 'Save',
  handler:
   function () {
     PanelData.submit({
       waitMsg: 'Loading...',
       url: 'Handlers/ХХХ.ashx?pid=' + pid + ...,
       success: function (form, action) { //true
                    }
       failure: function (form, action) { //false
                      alert('Error!!!')
                 }
     });
   }
});

Когда с сервера пришло: true срабатывает success
Когда с сервера пришло: false срабатывает failure

Проблема в том, что надо отправить с сервера ошибку, что бы видеть что не так сработало на стороне Сервера.
У меня срабатывает код только если приходит с Сервера чистые:
Все хорошо: true
Ошибка: false

Гуглил, везде пишут, что надо отправлять данные с сервера так:
Все хорошо: true или success
{ "success": "true"}

Ошибка: false или failure
{ "success": "false", "message": "Error message goes here." }


Например, если все хорошо и приходит "{ "success": "true"}", то срабатывает failure (((

Подскажите, пожалуйста, что не так делаю !!!

Ex_Soft 23.05.2012 17:40

Цитата:

Сообщение от potkin (Сообщение 176233)
если все хорошо и приходит "{ "success": "true"}", то срабатывает failure

Ext.form.Basic.submit()
Цитата:

{
    "success":*!*false*/!*, // note this is Boolean, not string
    "msg":"You do not have permission to perform this operation"
}


potkin 23.05.2012 18:11

Ex_Soft,
Во блин - с примера всё отлично сработало .....

potkin 25.05.2012 01:24

С Вашего позволения ещё вопросик:
Загрузка файлов на сервер
Ошибка, которую показывает консоль Хрома:
Uncaught Ext.Error: You're trying to decode an invalid JSON String: <pre style="word-wrap: break-word; white-space: pre-wrap;">{'success':false,'msg':'В стадии разработки!!!'}</pre>

То есть долбанный <pre в JSON String !!!
Код Панели с полем для загрузки файлов на Сервер:
var PanelData = new Ext.create('Ext.form.Panel', {
        title: 'Upload a Photo',
        width: 400,
        bodyPadding: 10,
        frame: true,
        items: [{
            xtype: 'filefield',
            name: 'photo',
            fieldLabel: 'Photo',
            labelWidth: 50,
            msgTarget: 'side',
            allowBlank: false,
            anchor: '100%',
            buttonText: 'Select Photo...'
        }],
        buttons: [{
            text: 'Upload',
            handler: function () {
                PanelData.submit({
                    url: 'Handlers/ХХХ.ashx?pid=' + pid,
                    waitMsg: 'Uploading your photo...',
                    success: function (fp, o) {
                        Ext.Msg.alert('Success', 'Your photo has been uploaded.');
                    },
                    failure: function (form, action) {
                        switch (action.failureType) {
                            case Ext.form.action.Action.CLIENT_INVALID:
                                Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                                break;
                            case Ext.form.action.Action.CONNECT_FAILURE:
                                Ext.Msg.alert('Failure', 'Ajax communication failed');
                                break;
                            case Ext.form.action.Action.SERVER_INVALID:
                                Ext.Msg.alert('Failure', action.result.msg);
                        }
                    }
                });
            }
        }]
    });


Гуглил ошибка с бородой, то есть извесный факт.
Пробовал и вместо
ContentType = "text/plain";
ставить
ContentType = "application/json";
исправило ситуацию, но частично, то есть для некоторых браузеров срабатывает, для некоторых нет и типов файлов.

Кто сталкивался подскажите что делать.
Юзаю АСП.НЕТ 4.0

Ex_Soft 25.05.2012 09:45

Цитата:

Сообщение от potkin (Сообщение 176477)
То есть долбанный <pre в JSON String !!!

А откель он там вообще взялсо? Выхлоп серванта д.б.:
Код:

context.Response.ContentType = "text/html";
context.Response.Write("<html><body><textarea>{ \"success\": \"true\", \"data\": { \"contactId\": \"contact id\", \"file\": \""+FileName+"\" } }</textarea></body></html>");

Цитата:

Сообщение от Connection.js
if (doc.body) {
    if (/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // *!*json response wrapped in textarea*/!*
        response.responseText = *!*firstChild*/!*.value;
    } else {
        response.responseText = doc.body.innerHTML;
    }
}


potkin 25.05.2012 15:45

Ex_Soft,
А это:
if (doc.body) {
    if (/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)) { // json response wrapped in textarea
        response.responseText = firstChild.value;
    } else {
        response.responseText = doc.body.innerHTML;
    }
}

куда "вставить", если не секрет ?

Ex_Soft 25.05.2012 17:18

Цитата:

Сообщение от potkin (Сообщение 176577)
А это
...
куда "вставить", если не секрет ?

Улыбнуло... Это ж я Вам, так сказать, первоисточник, сиречь - исходник цицировал:
Цитата:

Сообщение от Connection.js
C ext\src\data\Connection.js

potkin 29.05.2012 17:30

Ключевой момент был:
context.Response.ContentType = "text/html";

Ex_Soft 30.05.2012 09:27

Ну, дык:
Цитата:

Сообщение от http://docs.sencha.com/ext-js/4-0/#!/api/Ext.form.Basic-method-hasUpload
The server response is parsed by the browser to create the document for the IFRAME. If the server is using JSON to send the return object, then the Content-Type header must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.



Часовой пояс GMT +3, время: 20:53.