我已经注册了 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/