The 'Uncaught SyntaxError: Unexpected token : ' in jsonp

天大地大妈咪最大 提交于 2019-12-20 06:19:35

问题


I have already get the response json data from server to browser, but it is confused that the data can not be displayed in the browser and I found the error in the console that told me 'Uncaught SyntaxError: Unexpected token :'. Here is my code in node js.

function callFacebook(){
$.ajax({
    url: "http://192.168.37.179:8888/facebook/connect?callback_=[TIMESTAMP]",
        type: "GET",
        dataType: "jsonp",
        jsonp:"jsonp",
    cache: true,
    timeout: 5000,
    success: function(data) {
        execute(data);
    },
    error:function() { console.log('Uh Oh!'); }
});

} and here is the response json data: res.header('Content-Type','application/json'); res.header('Charset','utf-8'); res.send({"something": "father"});


回答1:


From the server you are sending just normal JSON data, but on client you are expecting JSONP. The response from server is not JSONP and browser does throw exception as syntax is wrong.

If you need to send JSONP from server, then if you are using express add extra use:

app.configure(function() {
  app.set('jsonp callback', true);
});

Then to send JSONP just slightly change res. You don't need to set any header anymore, as they will be automatically detected:

res.jsonp({ hello: 'world' });

On client side, jQuery will add callback it self, so use just this simplified way:

$.ajax({
  url: "http://192.168.37.179:8888/facebook/connect",
  type: 'GET',
  dataType: 'jsonp',
  cache: true,
  timeout: 5000,
  success: function(data) {
    console.log(data)
  },
  error: function(xhr, status, error) {
    console.log('error[' + status + '] jsonp');
  }
});

As well if your node is proxied through nginx or any other web platform, don't forget to enable utf8 encoding there.



来源:https://stackoverflow.com/questions/17406990/the-uncaught-syntaxerror-unexpected-token-in-jsonp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!