jquery.ajax()中的错误CSRFToken post call phonegap

时间:2013-11-05 12:11:09

标签: jquery cordova token csrf

你好我想发一个ajax电话。我使用Phonegap 2.8.0,jqm 1.3.2和Xcode这里是我的代码

window.SavePhoto= function() {

    try{ 
        var txtComment = $('#txtComment').val();
        var cameraImage = $('#cameraImage').attr('src');  
        var request_url = sessionStorage.getItem('CategoryLink');
       var X_CSRFToken = sessionStorage.getItem("X_CSRFToken");

        console.log('token=' + X_CSRFToken);
        console.log('cameraImage==' + cameraImage);        
        console.log("request_url==" + request_url);  
        console.log('txtComment==' + txtComment);

        if(!cameraImage){
            alert('Cannot save without select image','Image Required', 'Ok');            
            return;
        }
        $.ajax({
            url: request_url ,
            type: 'POST',
            contentType: 'multipart/form-data', 
            data:{"comment":txtComment,"photo_file":cameraImage}, 
            headers: {Cookie:cookie_saved,'X-CSRF-Token': X_CSRFToken}, 
            success: function (result,status,xhr) {
                if (! status.success) { 

                } else { 
                }
                alert ('message=' + JSON.stringify(status));
            },
            error: function (xhr,status,error)
            {
                alert(JSON.stringify(error));
            }
        });

    }

    catch(e){alert(e);}
    console.log('save photo function exit');

}

Phonegap应用程序在成功函数发生之前崩溃并给我以下日志。经过分析发现我可能会给出无效的CSRFToken。

2013-11-05 16:44:20.239 Appname[5388:a0b] Suid token=b1d950c3-2d82-48f2-9867-b4bcc0c4ae08
2013-11-05 16:44:20.240 Appname[5388:a0b] cameraImage==assets-library://asset/asset.JPG?id=B859F94D-B670-4251-9A4A-C14ACCC8CDD1&ext=JPG
2013-11-05 16:44:20.240 Appname[5388:a0b] request_url==http://jdev104p.jalf.com/rest/users/42547/photos/albums/messages
2013-11-05 16:44:20.240 Appname[5388:a0b] txtComment==dfs


    2013-11-05 16:44:20.241 Appname[5388:a0b] -[__NSCFDictionary length]: unrecognized selector sent to instance 0xb364d70
    2013-11-05 16:44:20.244 Appname[5388:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary length]: unrecognized selector sent to instance 0xb364d70'
    *** First throw call stack:
    (
        0   CoreFoundation                      0x001725e4 __exceptionPreprocess + 180
        1   libobjc.A.dylib                     0x030c28b6 objc_exception_throw + 44
        2   CoreFoundation                      0x0020f903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
        3   CoreFoundation                      0x0016290b ___forwarding___ + 1019
        4   CoreFoundation                      0x001624ee _CF_forwarding_prep_0 + 14
        5   Foundation                          0x019b1b2d -[NSConcreteMutableAttributedString replaceCharactersInRange:withString:] + 39
        6   Foundation                          0x019b279a -[NSConcreteMutableAttributedString initWithString:attributes:] + 293
        7   UIKit                               0x00585116 -[UILabel _setText:] + 97
        8   UIKit                               0x005852d4 -[UILabel setText:] + 40
        9   UIKit                               0x008b26aa -[UIAlertView(Private) setBodyText:] + 74
        10  UIKit                               0x008bdde6 -[UIAlertView setMessage:] + 40
        11  UIKit                               0x008be45e -[UIAlertView initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:] + 134
        12  Appname                           0x00027be6 -[CDVNotification showDialogWithMessage:title:buttons:defaultText:callbackId:dialogType:] + 342
        13  Appname                           0x00028016 -[CDVNotification alert:] + 406
        14  Appname                           0x0006bb2c -[CDVCommandQueue execute:] + 1132
        15  Appname                           0x0006b25b -[CDVCommandQueue executePending] + 683
        16  Appname                           0x0006ada9 -[CDVCommandQueue enqueCommandBatch:] + 153
        17  Appname                           0x0006af56 -[CDVCommandQueue fetchCommandsFromJs] + 182
        18  Appname                           0x0006ae6f -[CDVCommandQueue maybeFetchCommandsFromJs:] + 159
        19  libobjc.A.dylib                     0x030d481f -[NSObject performSelector:withObject:] + 70
        20  Foundation                          0x019c1c18 __NSThreadPerformPerform + 285
        21  CoreFoundation                      0x000fb8af __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
        22  CoreFoundation                      0x000fb23b __CFRunLoopDoSources0 + 235
        23  CoreFoundation                      0x0011830e __CFRunLoopRun + 910
        24  CoreFoundation                      0x00117b33 CFRunLoopRunSpecific + 467
        25  CoreFoundation                      0x0011794b CFRunLoopRunInMode + 123
        26  GraphicsServices                    0x045109d7 GSEventRunModal + 192
        27  GraphicsServices                    0x045107fe GSEventRun + 104
        28  UIKit                               0x003d894b UIApplicationMain + 1225
        29  Appname                           0x000029d6 main + 134
        30  Appname                           0x00002945 start + 53
        31  ???                                 0x00000001 0x0 + 1
    )
    libc++abi.dylib: terminating with uncaught exception of type NSException

1 个答案:

答案 0 :(得分:1)

花了好几个小时后我发现这个工作。有一点很清楚我们无法通过Ajax Jquery上传照片。我们必须使用filetransfer插件。这是我的工作代码。另一件事我们必须使用cordova 2.9.0而不是cordova 2.8.0,因为相机中有一个错误getpicture FILE_URI

window.SavePhoto= function() {

    try{ 
        var txtComment = document.getElementById('txtComments');
        var cameraImage = $('#cameraImage').attr('src');  
        var request_url = sessionStorage.getItem('CategoryLink');
        var X_CSRFToken = sessionStorage.getItem('X_CSRFToken');
        var cookies= X_CSRFToken;
        var lblpath = document.getElementById('lblpath');
        var fileURI= lblpath.innerHTML;



        if(!cameraImage){
            msgAlert('Cannot save without select image','Image Required', 'Ok');            
            return;
        }  

        var options = new FileUploadOptions();
        options.fileKey = "photo_file";
        options.mimeType = "image/jpeg";
        options.chunkedMode = false; 
        options.fileName=    fileURI.substr(fileURI.lastIndexOf('/')+1);
        options.params = {
            'comment': txtComment.value 
        };
        options.headers = {
            //'X-CSRFToken': csrfToken,
            Cookie: cookies
        }; 
       console.log('options=' + JSON.stringify( options));
        var ft = new FileTransfer();
        ft.upload(fileURI, encodeURI(request_url), win, fail, options); 
    } 
    catch(e)
    {
        msgAlert(e);
    }
    console.log('save photo exit');

}
var win=function (r) {
    console.log("Code = " + r.responseCode);
    console.log("Response = " + r.response);
    console.log("Sent = " + r.bytesSent);
}

var fail=function (error) {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
}