首页 > 解决方案 > Reading Nested JSON in a PHP Response from form.submit and NOT a Store

问题描述

I'm building a Web App using ExtJS 6.0.x. In one part, the users can upload an excel file and then I'll parse it and save the data to the backend.

The PHP I'm calling for the upload and parsing returns a nested JSON object whose structure is something like this:

{
    "success":false,
    "message":"Fail",
    "row_error_object_array":[{"data1":"val1","data2":"val2","data3":"val3","data4":"val4","data5":["array"]}],
    "overall_error_array":[]
}

Depending on the success or failure, the error arrays may or may not have values.

So far, I'm able to return this format back to the ExtJS framework, from my PHP. I'm able to get the non-array values, success and message, by doing something like this:

failure: function (form, action) {

    console.log('fail hit!');

    var data = Ext.JSON.decode(action.response.responseText);

    console.log('action is = ' + action);

    var success_ = data.success;
    var message_ = data.message;
    var row_error_ = data.row_error_object_array;
    var overall_error_ = data.overall_error_array;

    console.log('succees: ' + success_);
    console.log('message: ' + message_);
    console.log('row_error: ' + row_error_);
    console.log('overall_error: ' + overall_error_);


    var row_error_object = Ext.JSON.decode(row_error_);
    var overall_error_object = Ext.JSON.decode(overall_error_);

    console.log('row_error_object: ' + row_error_object);
    console.log('overall_error_object: ' + overall_error_object);

    if(row_error_.length > 0){
        console.log('row error present!!');
        console.log('row error data1 = ' + row_error_.data1);
        console.log('row error data2 = ' + row_error_.data2);
        console.log('row error data3 = ' + row_error_.data3);
        console.log('row error data4 = ' + row_error_.data4);
        console.log('row error data5 = ' + row_error_.data5);
    }


},

In this case, the success case isn't of interest since the error array are blank.

However, the logs show these:

row_error: [object Object]
row error data1 = undefined
row error data2 = undefined
row error data3 = undefined
row error data4 = undefined
row error data5 = undefined

Not sure what I'm doing wrong here, ExtJS knows they're an object, but when I try to do the object.property trick, it shows me undefined.

How do I deserialize nested JSON Responses from the server? Or are there any good workarounds for this?

标签: phpjsonextjsextjs4.2

解决方案


One JSON.decode is enough. And you try use row_error_array like object - it's wrong. You can get data keys of first element in your array:

console.log('row error data1 = ' + row_error_[0].data1);

fiddle


推荐阅读