简体   繁体   中英

jQuery AJAX JSONP error “Unexpected token”

I'm trying to make a cross domain JSONP call in Chrome, but the I keep getting back "Uncaught SyntaxError: Unexpected token :" I've tried: changing the response content type, setting xhr headers, JSON.stringify, just about most of the solutions offered on here but nothing worked so far :-(

 $.ajax({
                type: "POST",
                url: "https://www.virustotal.com/vtapi/v2/url/report",
                crossDomain: true,
                contentType: "application/json; charset=UTF-8",
                dataType: 'jsonp',
                data: {
                    apikey: "*",
                    resource: "http://www.1001freefonts.com/font/BaroqueScript.zip"
                },
                jsonp: false,
                jsonpCallback: receive,
                success: function (data, textStatus, jqXHR) {
                    console.log("Data retrieved: " + data);
                }
            }).done(function () {
                console.log('I think we are done here');
            })
        .error(function (e) {
            console.log(arguments);
            console.log('something went funny here');
        })
        .complete(function (xhr, status) {

            console.log("complete");
        if (status === 'error' || !xhr.responseText) {
            console.log('error');
        }
        else {
            console.log("data found:" + xhr.responseText);
            //...
        }
    });
    });

    function receive(saveData) {
        if (saveData == null) {
            console.log("DATA IS UNDEFINED!");  // displays every time
        }
        console.log("Success is " + saveData);  // 'Success is undefined'
    }

In the debugger I can see the response

{"permalink": "https://www.virustotal.com/url/b5b546fdbb49a2258e951c5e568a52655c65ac56112e39d15af0954a53b36772/analysis/1360339512/", "url": "http://www.1001freefonts.com/font/BaroqueScript.zip", "response_code": 1, "scan_date": "2013-02-08 16:05:12", "scan_id": "b5b546fdbb49a2258e951c5e568a52655c65ac56112e39d15af0954a53b36772-1360339512", "verbose_msg": "Scan finished, scan information embedded in this object", "filescan_id": "b7e13c0242e9690aba1f3da4b73d9c2e99a9b7fd03f542b55e694a34aaf9eca8-1360339519", "positives": 0, "total": 35, "scans": {"CLEAN MX": {"detected": false, "result": "clean site"}, "MalwarePatrol": {"detected": false, "result": "clean site"}, "ZDB Zeus": {"detected": false, "result": "clean site"}, "K7AntiVirus": {"detected": false, "result": "clean site"}, "Quttera": {"detected": false, "result": "clean site"}, "Yandex Safebrowsing": {"detected": false, "result": "clean site"}, "MalwareDomainList": {"detected": false, "result": "clean site"}, "ZeusTracker": {"detected": false, "result": "clean site"}, "zvelo": {"detected": false, "result": "clean site"}, "Google Safebrowsing": {"detected": false, "result": "clean site"}, "BitDefender": {"detected": false, "result": "clean site"}, "Opera": {"detected": false, "result": "clean site"}, "G-Data": {"detected": false, "result": "clean site"}, "C-SIRT": {"detected": false, "result": "clean site"}, "Sucuri SiteCheck": {"detected": false, "result": "clean site"}, "VX Vault": {"detected": false, "result": "clean site"}, "ADMINUSLabs": {"detected": false, "result": "clean site"}, "SCUMWARE.org": {"detected": false, "result": "clean site"}, "Dr.Web": {"detected": false, "result": "clean site"}, "AlienVault": {"detected": false, "result": "clean site"}, "Malc0de Database": {"detected": false, "result": "clean site"}, "SpyEyeTracker": {"detected": false, "result": "clean site"}, "Phishtank": {"detected": false, "result": "clean site"}, "Avira": {"detected": false, "result": "clean site"}, "Antiy-AVL": {"detected": false, "result": "clean site"}, "Comodo Site Inspector": {"detected": false, "result": "clean site"}, "Malekal": {"detected": false, "result": "clean site"}, "ESET": {"detected": false, "result": "clean site"}, "SecureBrain": {"detected": false, "result": "unrated site"}, "Netcraft": {"detected": false, "result": "clean site"}, "ParetoLogic": {"detected": false, "result": "clean site"}, "URLQuery": {"detected": false, "result": "unrated site"}, "Wepawet": {"detected": false, "result": "unrated site"}, "Minotaur": {"detected": false, "result": "clean site"}}}

I've verified it on http://jsonlint.com/ and it shows that it's a valid JSON.

Here are the Response Headers

cache-control:no-cache
content-encoding:gzip
content-length:695
content-type:application/json
date:Wed, 13 Feb 2013 12:00:33 GMT
server:Google Frontend
status:200 OK
vary:Accept-Encoding
version:HTTP/1.1

Anyone have any ideas/suggestions?

After thorough testing, it was evident that it's not possible to capture the JSON object results when ajax is expecting JSONP in return (due to cross-domain restrictions). Even though the response status = 200.

I've been testing using jQuery AJAX calls, in attempt to see if the result can still be captured - despite there's Parsing Error thrown by the browser - but it didn't seem that's possible. It looks like that the Response Text arrives in the header after JS work is completed.

As @Florian F. @Likwid_T @Christoph have suggested above, a server-side script is definitely required to make it working properly. Other developers seem to be keen on using a proxy written in C# as a solution.

JSONP doesn't work out of the box.

JSONP bypasses the cross-domain restriction by loading the result in a script tag.

Basically, your server has to be JSONP-enabled.

Do whatever needs to be done on your server side then right before sending the response :

  1. Check if the request has "_callback" set
  2. If set, wrap your content with the value of _callback.
  3. Send your data

Code example in PHP :

$responseString = '{"smthing":"val","smthingelse":"val2"}';
if (isset($_REQUEST['_callback'])) {
    $responseString = $_REQUEST['_callback'] . '(' . $responseString . ');';
}

It'll execute your 'done' anonymous function with the right arguments. (JQuery handles everything else)

Christoph is right you need to encase your answer in your callback function, in your case at the end of the PHP file:

echo $_GET['receive'] . '(' . json_encode($yourResultObject) . ');';

or if you need a more complex object

echo $_GET['receive'] . '(' . json_encode(array(name1 => object1, name2 => object2, name3 => object3)) . ');';

You might have to tweak a bit, but basically whenever I get Unexpected token is almost always a syntax error that makes jQuery not get my callback function.

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