简体   繁体   English

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

[英]How to store the JSON value fetch from a URL using JQuery?

I am new to JQuery. 我是JQuery新手。 I am trying to develop a small travel website for checking PNR. 我正在尝试开发一个小型旅行网站来检查PNR。 I am currently using an API provided by one of the travel company. 我目前正在使用旅游公司之一提供的API。 As soon as we hit the API Url, browser displays the result in JSON format. 一旦我们点击了API网址,浏览器就会以JSON格式显示结果。

I am using JQuery, JS and HTML. 我正在使用JQuery,JS和HTML。 I want to know how to store the JSON value (in string format) retrieved from hitting an API, in a variable and use it later in the script. 我想知道如何将通过点击API检索到的JSON值(以字符串格式)存储在变量中,并在以后的脚本中使用它。

PS: Though I have found many answer in Stackoverflow but none of the result works. PS:虽然我在Stackoverflow中找到了很多答案,但是没有一个结果有效。 Kindly help with the appropriate value. 请帮助以适当的价值。

Sample Code: (I am using one textbox and button) 示例代码:(我正在使用一个文本框和一个按钮)

    <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()"/>

Below is the JSON value getting from server 下面是从服务器获取的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}

Kindly also help how to read both the objects and array in the given JSON. 请帮助您读取给定JSON中的对象和数组。

You can use ajax to fetch the result from the url 您可以使用ajax从网址获取结果

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));
    }
});

You just need to parse JSON and how to read each object. 您只需要解析JSON以及如何读取每个对象。 This should give you good start 这应该给您一个好的开始

$.ajax({
    type: "GET",
    url: "http://api_website/pnr"+pnr,
    data: data,
    success: function(resultData) { 
        console.log(resultData);

        var to_station = resultData.to_station;
        var trains = resultData.train;
        var passengers = resultData.passengers;

        alert("Station Name: "to_station.name);
        alert("Passengers: "passengers.booking_status);


    },
    error(function() { 
        alert("Something went wrong"); 
    }
});

You can read more bout how to read JSON here . 您可以在此处了解更多有关如何读取JSON的信息

$.ajax({
  method: "GET",
  url: url
})
  .done(function( data ) {
    console.log(data)
    // see what properties you need from data object and save it to variable
    var data = data
  });

First thing, 第一件事

Use a javascript file....API calls are better off done in a js file rather than in a script tag. 使用javascript文件。...API调用最好在js文件而不是在脚本标记中完成。 Second thing, if you want to store it in a json format, you can store it in a value like the way you have declared your url variable. 第二件事,如果要以json格式存储它,可以将其存储为一个值,例如声明url变量的方式。 Since, you are fetching the data, I'm assuming this is a get request, you can find more information about them in the following links - 由于您正在获取数据,因此我假设这是一个获取请求,您可以在以下链接中找到有关它们的更多信息-

  1. https://www.sitepoint.com/ajaxjquery-getjson-simple-example/ https://www.sitepoint.com/ajaxjquery-getjson-simple-example/
  2. https://api.jquery.com/jquery.get https://api.jquery.com/jquery.get

Also, if the data isn't very sensitive, you can store it in the local storage of your browser, so that you can access it later on in other web pages as well. 另外,如果数据不是很敏感,则可以将其存储在浏览器的本地存储中,以便以后也可以在其他网页上访问它。

In your current json data, I would say that if you declare it to a variable say apiResult Your to_station would be apiResult.to_station , the lng value would be apiResult.to_station.lng and so on. 在当前的JSON数据,我会说,如果你把它声明一个变量说apiResult你to_station将apiResult.to_station ,液化天然气价值将是apiResult.to_station.lng等。

Hope any of this helps, and good luck. 希望这对您有所帮助,并祝您好运。

Everyone already added the AJAX examples, so I will leave that out. 每个人都已经添加了AJAX示例,因此我将其省略。

So for reading the objects, you just have to parse what you need through various means, if you know what the object looks like and exactly what you need you can use dot notation. 因此,对于读取对象,您只需通过各种方式解析所需的内容,如果您知道对象的外观以及所需的内容,则可以使用点表示法。 If you are looking to grab things more dynamically you can using higher order functions or for loops as well as Object prototypes example getting the entries ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries ) 如果您希望动态地抓取事物,可以使用高阶函数或for循环以及获取条目的对象原型示例( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Global_Objects / Object / entries

You might consider using localStorage for storing the information depending on what you are using it for which is a built-in Web API here is MDN's definition 您可能会考虑使用localStorage来存储信息,具体取决于您使用的信息是哪种内置Web API,这是MDN的定义

The read-only localStorage property allows you to access a Storage object for the Document's origin; 只读的localStorage属性允许您访问文档来源的存储对象; the stored data is saved across browser sessions. 存储的数据跨浏览器会话保存。 localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed. localStorage与sessionStorage相似,不同之处在于,尽管localStorage中存储的数据没有到期时间,但页面会话结束时(即关闭页面时),存储在sessionStorage中的数据将被清除。

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

You may want to use AJAX. 您可能要使用AJAX。 You have to be sure how the server will retrieve the data. 您必须确定服务器将如何检索数据。 If it is in a JSON format do: 如果为JSON格式,请执行以下操作:

<script>
    function search_pnr(){
        var pnr = $('#input_pnr').val();
        var result;
        var url = "http://api website/pnr"+pnr;
        $.getJSON( url, function( data ) {
            result = data;
            $.each( data, function( key, value ) {
                // whatever with keys and values if needed
            }
        );

    }
</script>

Ref w3 Schools Ref w3学校

JQuery official website jQuery官方网站

All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that: 当前所有的浏览器都内置了本机JSON支持。因此,只要您不使用IE6 / 7之类的史前浏览器,就可以像这样轻松地做到这一点:

var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'

For more info kindly visit link 欲了解更多信息,请访问链接

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

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