简体   繁体   中英

How can I read data from a URL?

I have a function in javascript which I hard-coded as of now:

function getCarData() 
{
    return 
    [
        {car: "Nissan", year: 2009, chassis: "black", bumper: "black"},
        {car: "Nissan", year: 2006, chassis: "blue", bumper: "blue"},
        {car: "Chrysler", year: 2004, chassis: "yellow", bumper: "black"},
        {car: "Volvo", year: 2012, chassis: "white", bumper: "gray"}
    ];
}

Now.. this was just to unit test whether the code will work or not.. But now it is working..

I am generating this data on backend and am mapping it to the directory on server (which is localhost at the moment)

So if I go to localhost:5000/cardata I have exact same data ie

[
    {car: "Nissan", year: 2009, chassis: "black", bumper: "black"},
    {car: "Nissan", year: 2006, chassis: "blue", bumper: "blue"},
    {car: "Chrysler", year: 2004, chassis: "yellow", bumper: "black"},
    {car: "Volvo", year: 2012, chassis: "white", bumper: "gray"}
];

What changes I should made on my javascript file in order to make this work?

$(document).ready(function()
{
    $.get('/cardata', function(data)
    {
        alert(data[0].car) //alerts "Nissan"
    });
})

don't forget to include the jQuery library

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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