PHP Ajax响应在由javascript解析时给出未定义的数据

时间:2019-04-12 23:34:28

标签: javascript php json

今天早些时候并没有给出错误,但是现在每次文件上传我都得到

Unexpected number in JSON at position 161

我查看了文件上传JSON,并了解到该文件传递了非法的0:

    {
    "ftype":"file",
    "meta":"prem-sal2.jpg",
    "fname":"screenshot1",
    "id":"392",
    "epn":"63",
    "action":"updategamefiles",
    "file":{
      "name":"prem-sal2.jpg",
      "type":"image/jpeg",
      "tmp_name":"/tmp/phpxPZNCL",
      "error":0,
      "size":968969
     }
    }

以下是选择文件的javascript:

else if (fieldclass[1].indexOf("screenshot") >= 0) {
                ftype = 'file';
                document.getElementsByClassName(fname)[0].getElementsByTagName('label')[0].innerHTML = 'Loading';
                meta = this.files[0].name;
                file = this.files[0];
                 if( file.type === "image/jpg" || file.type === "image/png"  || file.type === "image/gif" || file.type === "image/jpeg") {
                 extension = true;
                } 
            }

那么如何避免在文件JSON中得到该错误:0?

嗯,忘了添加Ajax请求:

    if (extension === true) {
    var data = new FormData();
    data.append('file', file);
    data.append('ftype', ftype);
    data.append('meta', meta);
    data.append('fname', fname);
    data.append('id', id);
    data.append('epn', epn);
    data.append('action', 'updategamefiles');
    var value = jQuery.ajax({
        data : data,
        type: 'POST',
        url: ajaxurl,
        cache: false,
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        dataType: 'json',
        success: function(data, textStatus, jqXHR) {    

            if( data.response == 'SUCCESS' ){
                document.getElementsByClassName(data.fname)[0].getElementsByTagName('label')[0].innerHTML = 'Success';
                document.getElementsByClassName(data.fname)[0].getElementsByTagName('label')[0].style.backgroundImage = "url('" + data.thumb +"')";

            } if( data.response == 'ERROR' ){
            document.getElementsByClassName(data.fname)[0].getElementsByTagName('label')[0].style.background = '#fdd2d2';
            document.getElementsByClassName(data.fname)[0].getElementsByTagName('label')[0].innerHTML = 'Error';

            }
            },
        error: function(jqXHR, textStatus, errorThrown){    


            }
        })
        }

1 个答案:

答案 0 :(得分:0)

事实证明,在响应来自php后端的响应而回显编码的json之后,我不得不die();,但是我没有将额外的数据添加到json中导致问题。