jQuery ajax返回意外的数据类型

attempting to implement some server side error checking for input in the very useful "handsontable" jscript library.

the following call works great:

jQuery.ajax({
    url: "index.php?option=com_catalogscontroller=batchsave",
    data: {"formData": querydata.getData().splice( 0, 1 ) },
    dataType: 'JSON',
type: 'POST',
    success: function ( response ) {
    if( response.success ) {
    } else {
    querydata.loadData( response.data );
    }
}
});

I thought the most effective way to do error checking is on the server (PHP) side, to create a multidimensional array to track any errors discovered by the server and then return that array with the form data in the same ajax call. So I modified the server code to return both the form data and the error array back to the javascript ajax call. i.e.:

if( !empty( $errors ) ) // $errors is an multi dimensional array same size as the form data
    $result['success'] = false;
    $result['msg'] = 'There were errors detected';
    $result['data']['form'] = $formData;
    $result['data']['errors'] = $errors;
}
echo json_encode( $result );

and then on the client side, the javascript routine above has been modified to:

jQuery.ajax({
    url: "index.php?option=com_catalogscontroller=batchsave",
    data: {"formData": querydata.getData().splice( 0, 1 ) },
    dataType: 'JSON',
    type: 'POST',
    success: function ( response ) {
    if( response.success ) {
    } else {
            formErrors = response.data.errors; // formErrors is a global
    querydata.loadData( response.data.form );
    }
}
});

The original function of the form is preserved (the form data is retrieved and properly inserted in the html), but formErrors returns with a result to me that is baffling. An alert immediately after the assignment 'alert( formErrors )' shows something like a list:

true,true,false,true,true

and I can also alert on a specific index without problem e.g. alert( formErrors[0][2] ); would display 'false'. But outside of the ajax call, the array seems to be inaccessible, giving 'undefined' errors. And both in the ajax call, and in routines outside of the ajax call alert( typeof formErrors ) displays 'object' and alert( formErrors) gives the same comma list as above, but I don't want an object, I am expecting an array OR i'd be happy with an object as long as i could access it by indices. What am I missing here?

查看全部
duanqian2368
duanqian2368
2013/09/10 22:10
  • php
  • arrays
  • ajax
  • jquery
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复