简体   繁体   中英

How to get JSON string from URL with Javascript?

I'm trying to get JSON string from an URL:

http://megarkarsa.com/gpsjson.php

The URL echoes JSON location value to be shown as string, with this result for example:

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

I need to get this string from javascript, so i can parse it later with JSON.parse(string).

I have tried to use getJson, but seems it can't be done since it's not real Json value, but string.

How can i do that? Every suggestion will be appreciated.

Why not just jQuery ?

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

or use php :

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

if you already did all and still not working, try :

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

The last solution is dangerous, use it if you trust the API you working with

As Michael Antonio pointed out, using Ajax would be the way to do it. Heres my code

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>

However, an error keeps cropping up. Here are the request/response headers, notice the response is force closing the connection.

Request

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

Response

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

Also notice that the content-type of the response is HTML, and should be JSON if you wish to parse the JSON using the above Ajax function I provided. The error coming back is not helpful whatsoever, meaning that the connection is being cut off or refused by making the Ajax call, and no data is being sent back.

You can do this as well :

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

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