javascript - 如何使用 Javascript/jQuery (Ajax) 检索 Google QPX 结果?

标签 javascript ajax json google-api restful-url

我已经注册了 Google API 控制台并设置了帐户和 API key ,但我的问题是如何从 Google QPX 检索结果。 什么原因导致以下错误?

为 Google 请求设置 json 查询

var FlightRequest = {
  "request": {
    "slice": [
      {
        "origin": "DCA",
        "destination": "LAX",
        "date": "2015-02-11"
      }
    ],
    "passengers": {
      "adultCount": 1,
      "infantInLapCount": 0,
      "infantInSeatCount": 0,
      "childCount": 0,
      "seniorCount": 0
    },
    "solutions": 20,
    "refundable": false
  }
}

请求数据并返回数据。

$.ajax({
 url: "https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXXX", 
 type: 'POST',
 dataType: 'json',
 contentType: 'application/json',
 data: FlightRequest,
 success: function (data) {
  alert(JSON.stringify(data));
},
  error: function(){
   alert("Cannot get data");
 }
});

错误: 我已经检查过我的 API key 并且是正确的。什么可能导致此问题?

status of 400 (Bad Request)

最佳答案

我已经通过使用 Google Chrome POSTMAN App 解决了这个问题并使用 JSON.stringify(); 将 Google json 发送请求(对象)转换为 $.ajax() 的字符串;以下是使用 jQuery 解决此问题的步骤。

首先为您的 Google json 请求创建一个变量: 我们将使用 Ajax 来检索数据。

var FlightRequest = {
      "request": {
        "slice": [
          {
            "origin": "DCA",
            "destination": "LAX",
            "date": "2015-02-11"
          }
        ],
        "passengers": {
          "adultCount": 1,
          "infantInLapCount": 0,
          "infantInSeatCount": 0,
          "childCount": 0,
          "seniorCount": 0
        },
        "solutions": 20,
        "refundable": false
      }
    };

使用 jQuery $.ajax(); 发送访问 key 内容类型数据请求

$.ajax({
     type: "POST",
     //Set up your request URL and API Key.
     url: "https://www.googleapis.com/qpxExpress/v1/trips/search?key=YOUR-API-KEY", 
     contentType: 'application/json', // Set Content-type: application/json
     dataType: 'json',
     // The query we want from Google QPX, This will be the variable we created in the beginning
     data: JSON.stringify(FlightRequest),
     success: function (data) {
      //Once we get the result you can either send it to console or use it anywhere you like.
      console.log(JSON.stringify(data));
    },
      error: function(){
       //Error Handling for our request
       alert("Access to Google QPX Failed.");
     }
    });

关于javascript - 如何使用 Javascript/jQuery (Ajax) 检索 Google QPX 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28311410/

相关文章:

javascript - AJAX 调用时锁定按钮

javascript - 使用 jQuery 使用 optgroup 填充选择

javascript - 使用 JQuery 切换 A 标签顺序

c# - 从后端(AJAX)在页面中运行 JavaScript?

javascript - jQuery Navigation 淡入淡出、隐藏、显示、反弹和计时

php - 使用 AJAX 将 Javascript 字符串发送到 PHP 文件,然后从文件返回数组

json - 通过 Powershell 中的变量解析/访问嵌套 JSON/Hashtable 数据时出现问题

javascript - Bootstrap 悬停图像显示示例

javascript - 如何自定义背景网格行

javascript - 文本框的垂直焦点