简体   繁体   English

使用Ajax的api调用中的响应错误

[英]Response error in api call with ajax

I want to retrieve the houseType and this is the api call using ajax. 我想检索houseType ,这是使用ajax的api调用。 Only Console.log for result is fine but the others show undefined . 只有Console.log可以得到result ,但是其他显示为undefined I don't know why it happens. 我不知道为什么会这样。

$.ajax({
    url: 'http://api/get.php',
    type: 'GET',
    crossDomain: true,
    datatype:'json',
    data:{
      HouseNo: 2001
    },
    success: function(result) {
      console.log(result);
      console.log(result.error);
      console.log(result.houses);
      console.log(result.houses.houseType);
      if (result.error == false) {
      window.location.href = "viewHouses.php"
    }
  },
  error: function(result) {
      alert("Error");
  }
});

The console log result is 控制台日志result

{"error":false,"houses":[{"houseType":"Mansion"}]}

but the logs of result.error and result.houses are undefined . 但是result.errorresult.houses的日志undefined What am I missing? 我想念什么?

As the jquery docs state: 如jquery docs所述:

"json": Evaluates the response as JSON and returns a JavaScript object. “ json”:将响应评估为JSON并返回一个JavaScript对象。 Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. 跨域“ json”请求将转换为“ jsonp”,除非该请求的请求选项中包含jsonp:false。 The JSON data is parsed in a strict manner; JSON数据是严格解析的。 any malformed JSON is rejected and a parse error is thrown. 任何格式错误的JSON都会被拒绝,并引发解析错误。

If you are requesting the data with a cross-origin request, the options should have a jsonp: false value: 如果要通过跨域请求来请求数据,则选项应具有jsonp: false值:

$.ajax({
    url: 'http://api/get.php',
    type: 'GET',
    crossDomain: true,
    datatype:'json',
    jsonp: false,

    data:{
        HouseNo: 2001
    },

    success: function(result) {
        // ...
    },

    error: function(result) {
        // ...
    }
});

To me this looks like you're actually logging a JSON(P) string of some sort. 对我来说,这似乎是您实际上正在记录某种JSON(P)字符串。 If the above does not work try parsing result with: 如果上述方法不起作用,请尝试使用以下方法解析result

try {
    var parsed = JSON.parse(result);
    console.log(parsed);
} catch(err) { console.log(err); }

I'm curious what this snippet would log. 我很好奇这段代码会记录什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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