Console并设置了帐户和API密钥,但我的问题是如何从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 密钥并且是正确的。什么会导致此问题?
状态为 400(错误请求)
我已经通过使用Google Chrome POSTMAN应用程序并使用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();
发送访问密钥、内容类型和数据请求
$.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.");
}
});
所以这是你的HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<input type="submit" id="submit" value="Submit">
<p id="demo"></p>
</body>
</html>
现在制作一个名为 test.js 的新文件,并将其放在与 HTML 文件相同的目录中。将下面的代码放在新的测试.js文件中
最后,在代码中添加您自己的 API 密钥(其中表示您的 API 密钥)
var sendRequest = function(){
var FlightRequest = {
"request": {
"slice": [
{
"origin": "LHR",
"destination": "LAX",
"date": "2018-9-10"
}
],
"passengers": {
"adultCount": 1,
"infantInLapCount": 0,
"infantInSeatCount": 0,
"childCount": 0,
"seniorCount": 0
},
"solutions": 10,
"refundable": false
}
};
$.ajax({
type: "POST",
url: "https://www.googleapis.com/qpxExpress/v1/trips/search?key=YOUR_API_KEY",
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(FlightRequest),
success: function (data) {
var myJSON = JSON.stringify(data.trips.tripOption[0].pricing[0].saleTotal);
console.log(myJSON);
document.getElementById("demo").innerHTML = myJSON;
},
error: function(){
alert("Access to Google QPX Failed.");
}
});
}
$(document).ready(function(){
$("#submit").click(function(){sendRequest();});
});
现在在上面的代码中,如果您想学习如何过滤结果,我将从 LHR 到 LAX 获得 1 个价格,请查看此链接