JQUERY-AJAX-JSON,无法将数据结果保存到cookie

时间:2016-10-06 13:25:11

标签: jquery html json ajax jquery-cookie

我一直在这个网站上搜索很多,并试图找到一个可能与此类似的问题。

我正在传递Json post请求并检索我期望的正确结果,但是在尝试将其保存到cookie时我没有运气。我使用js.cookie插件。

代码:

$(".image-upload").on('change', '#file-input', function() {
  if (this.files && this.files[0]) {
    var FR= new FileReader();
    FR.onload = function(e) {
        var datalogin = {
                appid: "100022211"
                , appsecret: "272018"
                , user: getCookie('myid')  //this cookie still work
                , file: e.target.result
            }
            $.ajax({ type: "post"
            , url: "https://myweb/api/account/upload_picture_base64"
            , data: JSON.stringify(datalogin)
            , contentType: "application/json; charset=utf-8",
            dataType: "json", //i can't use jsonp because this is post
            beforeSend: function () {

                console.log('start'); // log
            }
            , error: function (data, status) {
                console.log('error'); // log


                alert("Unknown error");
            }
            , success: function (data) {

                var p = data.picture;               
                var t = data.picture_type;
                setCookie('mypicturetype', t, '365');
                setCookie('mypicture', p, '365');
                console.log('success. data type : ' + getCookie('mypicturetype') + 'and pict= ' + getCookie('mypicture')); //tulis dalam log
                $(".mypicture").html("<img src='data:" + t + ";base64," + p + "' height='100%' width='100%'/>");
                //success update the picture in html but fail to play cookie
            }
        });

    };       
    FR.readAsDataURL( this.files[0] );
  }
});

我的帖子请求结果:

{"id":"2","username":"Yukon","name":"","email":"lordyukon@gmail.com","picture_type":"image\/jpeg","picture":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/\/gA8Q1JFQVRPUjogZ2Qta/\/Z","status":"0"}

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,但经过几次尝试和错误后,我发现你无法将base_64字符串直接保存到cookie中。

我建议你使用本地存储来保存这种类型的字符串,而不是强制cookie。

This Question give awesome solution for you