jQuery,ajax和jsonp的问题

Zac*_*oll 5 javascript ajax jquery json jsonp

我正在使用jsonp和ajax访问另一台服务器上的Web服务.这是jQuery:

$.ajax({
  type: 'GET',
  url: wsurl + 'callback=?',
  dataType: 'jsonp',
  crossDomain: true,
  error: function(data) {
    console.log('error', data);
  },
  success: function(data) {
    console.log('success', data);
  },
  complete: function() {
    console.log('done');
  }
});
Run Code Online (Sandbox Code Playgroud)

问题是正在调用错误回调.它给了我这个非常有用的信息:

{
  readyState: 4,
  status: 200,
  statusText: "success"
}
Run Code Online (Sandbox Code Playgroud)

这是我正在调用的json文件:

{
  "id": 0,
  "room_number": "0",
  "first_name": "Admin",
  "last_name": "Istrator",
  "password": "",
  "salutation": "Mr.",
  "telephone": "",
  "email": "",
  "description": "admin",
  "checkin_date": 915797106000,
  "checkout_date": 4071557106000,
  "last_login_date": 947333106000,
  "active_status": true,
  "created_date": 915797106000,
  "created_by": 0,
  "reference_id": ""
}
Run Code Online (Sandbox Code Playgroud)

我首先尝试使用getJSON jQuery方法,结果相同.以为我会尝试基础ajax方法,因为它有更多的控制权,但正如你所看到的,没有运气.那么,请注意我做错了什么?知道为什么它会抛出一个错误并给我一个statusText属性的成功值吗?

编辑

好吧,我在ajax调用中添加了一些选项,并从url中删除了回调参数.这是新的ajax调用:

  $.ajax({
    type: 'GET',
    url: wsurl,
    dataType: 'jsonp',
    crossDomain: true,
    error: function(xhr, textStatus, errorThrown) {
      console.log('textStatus: ' + textStatus);
    },
    success: function(data) {
      console.log('success');
      console.log(data);
    }
  });
Run Code Online (Sandbox Code Playgroud)

我收到了一个新的错误,我想这很好,但仍然没有用.区别在于textStatus现在是"parsererror".控制台也在json文件的第一行抛出语法错误:

Uncaught SyntaxError: Unexpected token :
Run Code Online (Sandbox Code Playgroud)

想法?

Jam*_*mie 1

好吧,有几件事引起了我的注意:

$.ajax({
  type: 'GET',
  #You do not need to append the callback as you have jsonp configured it will  do it    
  #automatically append the callback=<auto generated name>
  url: wsurl, 
  dataType: 'jsonp',
  crossDomain: true,
  error: function(data) {
    console.log('error', data);
  },
  success: function(data) {
    console.log('success', data);
  },
  complete: function() {
    console.log('done');
  }
});
Run Code Online (Sandbox Code Playgroud)

此外,您的返回似乎没有包含在 jsonp 工作所需的函数中。

<auto generated name>({ json object })
Run Code Online (Sandbox Code Playgroud)

回调函数将由 jquery 自动命名。因此,您需要一个接受回调参数并返回带有填充的 json 对象的服务。