如何从URL读取数据?

时间:2013-02-12 22:45:04

标签: javascript

我在javascript中有一个函数,我现在硬编码:

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"}
    ];
}

现在..这只是单元测试代码是否有效..但现在它正在工作..

我在后端生成这些数据并将其映射到服务器上的目录(目前是localhost)

所以,如果我去localhost:5000 / cardata 我有完全相同的数据,即

[
    {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"}
];

我应该对我的javascript文件进行哪些更改才能使其正常工作?

1 个答案:

答案 0 :(得分:1)

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

不要忘记包含jQuery库