gpt4 book ai didi

javascript - 如何使用 JQuery 存储从 URL 获取的 JSON 值?

转载 作者:行者123 更新时间:2023-12-03 01:22:43 24 4
gpt4 key购买 nike

我是 JQuery 新手。我正在尝试开发一个用于检查 PNR 的小型旅行网站。我目前正在使用一家旅游公司提供的 API。一旦我们点击 API Url,浏览器就会以 JSON 格式显示结果。

我正在使用 JQuery、JS 和 HTML。我想知道如何将从访问 API 中检索到的 JSON 值(字符串格式)存储在变量中,并稍后在脚本中使用它。

PS:虽然我在Stackoverflow上找到了很多答案,但没有一个结果有效。请帮助提供适当的值。

示例代码:(我使用一个文本框和按钮)

    <script>
function search_pnr(){
var pnr = $('#input_pnr').val();
var result;
var url = "http://api website/pnr"+pnr;

//Suggest the code here, to fetch the result from url and store in the variable result.

</script>

<input type="text" placeholder="Enter PNR" id ="input_pnr"/>
<input type="button" value="Search PNR" onclick="search_pnr()"/>

下面是从服务器获取的 JSON 值

{"to_station": {"lng": 77.2888291, "name": "ANAND VIHAR TERMINAL", "lat": 28.6118176, "code": "ANVT"}, "total_passengers": 1, "pnr": "6717552286", "journey_class": {"name": null, "code": "3A"}, "train": {"classes": [{"available": "N", "name": "SECOND AC", "code": "2A"}, {"available": "Y", "name": "THIRD AC", "code": "3A"}, {"available": "N", "name": "SECOND SEATING", "code": "2S"}, {"available": "N", "name": "FIRST AC", "code": "1A"}, {"available": "Y", "name": "AC CHAIR CAR", "code": "CC"}, {"available": "N", "name": "FIRST CLASS", "code": "FC"}, {"available": "N", "name": "3rd AC ECONOMY", "code": "3E"}, {"available": "N", "name": "SLEEPER CLASS", "code": "SL"}], "days": [{"code": "MON", "runs": "N"}, {"code": "TUE", "runs": "Y"}, {"code": "WED", "runs": "N"}, {"code": "THU", "runs": "Y"}, {"code": "FRI", "runs": "N"}, {"code": "SAT", "runs": "Y"}, {"code": "SUN", "runs": "N"}], "number": "22405", "name": "BGP-ANVT GARIB RATH"}, "from_station": {"lng": 86.9828131, "name": "BHAGALPUR", "lat": 25.2494829, "code": "BGP"}, "passengers": [{"booking_status": "CNF/G12/36/GN", "no": 1, "current_status": "CNF/-/0/GN"}], "reservation_upto": {"lng": 77.2888291, "name": "ANAND VIHAR TERMINAL", "lat": 28.6118176, "code": "ANVT"}, "response_code": 200, "boarding_point": {"lng": 86.9828131, "name": "BHAGALPUR", "lat": 25.2494829, "code": "BGP"}, "debit": 3, "doj": "25-08-2018", "chart_prepared": false}

还请帮助如何读取给定 JSON 中的对象和数组。

最佳答案

可以使用ajax从url中获取结果

var result;
var url = "http://api website/pnr"+pnr;
$.ajax
({
url: url,
type: 'GET',
dataType: 'json',
success: function(data)
{
result = data;
alert(JSON.stringify(data));
}
});

关于javascript - 如何使用 JQuery 存储从 URL 获取的 JSON 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51696828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com