简体   繁体   中英

Ajax error with the same data (parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data)

I've got two pages that use the same js-file to call certain PHP-file and get data from there in JSON format. Although the data that gets in the PHP-file AND data that gets out is exactly the same, Ajax on the second page returns 'parsererror' SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.

        $.ajax({
        type: 'POST',
        dataType: "json",
        data: {objtyp: this.objtyp, objid: this.objid},
        url: '/admin/getfieldsadd.php', 
        success: function(data) {
        //not going to happen
        },

        error: function (xhr, status, text) {
          switch (status) {
             case 404:
                 alert('File not found');
                 break;
             case 500:
                 alert('Server error');
                 break;
             case 0:
                 alert('Request aborted');
                 break;
             default:
                 alert('Unknown error: ' + status + " " + text);
            }
        }

So have anybody encountered the same problem?

This sounds reminiscent of the dreaded BOM . Excerpt from that link:

At the beginning of a page that uses a Unicode character encoding you may find some bytes that represent the Unicode code point U+FEFF BYTE ORDER MARK (abbreviated as BOM).

The BOM, when correctly used, is invisible.

Perhaps check that the file's encoding is set to UTF8 Without BOM .

Maybe a mime type error.

Try to add the beforeSend property like this in your AJAX call :

$.ajax({
    type: 'POST',
    dataType: "json",
    data: {objtyp: this.objtyp, objid: this.objid},
    url: '/admin/getfieldsadd.php',
    beforeSend: function(x) {
        if(x && x.overrideMimeType) {
            x.overrideMimeType("application/json");
        }
    },
    ...
}

It appears the trouble was in jQuery version. Now that it's updated all seems to work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM