繁体   English   中英

如何使用Javascript从URL获取JSON字符串?

[英]How to get JSON string from URL with Javascript?

我正在尝试从URL获取JSON字符串:

http://megarkarsa.com/gpsjson.php

URL回显JSON位置值以显示为字符串,例如:

{"BMS":[{"id":"PR01","type":"prajurit","lat":"-6.253310","long":"107.156219"},{"id":"PR02","type":"prajurit","lat":"-6.224084","long":"106.653069"},{"id":"PR03","type":"kendaraan","lat":"-6.244316","long":"106.649734"}]}

我需要从javascript获取此字符串,因此我可以稍后使用JSON.parse(字符串)解析它。

我曾尝试使用getJson,但似乎无法完成,因为它不是真正的Json值,而是字符串。

我怎样才能做到这一点? 每个建议都将不胜感激。

为什么不只是jQuery?

$.get('http://megarkarsa.com/gpsjson.php',function(data){
    console.log(data);
},'json');

或使用PHP:

<?php
$json=file_get_contents('http://megarkarsa.com/gpsjson.php');
$json=json_decode($json,true);
?>

如果你已经做了所有但仍然没有工作,请尝试:

$.get('http://megarkarsa.com/gpsjson.php',function(data){
    data = eval ("(" + data + ")");
    console.log(data);
});

最后一个解决方案很危险,如果您信任您使用的API,请使用它

正如迈克尔·安东尼奥指出的那样,使用Ajax将是实现这一目标的方法。 继承我的代码

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON</title>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script>
    $(function() {
        $.ajax({
            url: 'http://megarkarsa.com/gpsjson.php',
            type: 'GET',
            dataType: 'html',
            success: function(data, status, xhr)
            {
                $("#json").html(data);
            },
            error: function(xhr, status, error)
            {
                $("#json").html("Error: " + status + " " + error);
            }
        });
    });
    </script>
</head>
<body>
    <div id="json"></div>
</body>
</html>

但是,错误会不断出现。 以下是请求/响应标头,请注意响应是强制关闭连接。

请求

Host: megarkarsa.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://testsites.kalebklein.com/json1/json.html
Origin: http://testsites.kalebklein.com
Connection: keep-alive

响应

Connection: close
Content-Type: text/html
Date: Mon, 21 Sep 2015 01:52:56 GMT
Server: Apache
Transfer-Encoding: chunked
x-powered-by: PHP/5.4.36

另请注意,响应的内容类型是HTML,如果您希望使用我提供的上述Ajax函数解析JSON,则应该是JSON。 返回的错误无济于事,这意味着通过进行Ajax调用来切断或拒绝连接,并且没有数据被发回。

你也可以这样做:

str='{"BMS":[{"id":"PR01","type":"prajurit","lat":"-6.253310","long":"107.156219"},{"id":"PR02","type":"prajurit","lat":"-6.224084","long":"106.653069"},{"id":"PR03","type":"kendaraan","lat":"-6.244316","long":"106.649734"}]}'; //example string
obj=jQuery.parseJSON( (str)); //parse as json
$.each(obj, function (i, item) { //loop through each item in main obj
     $.each(item, function (i, y) { loop through each prop in item
         alert(y.id) //you can access the values like this others can be accessed via the dot notation such as y. prajurit
     });
});

暂无
暂无

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

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