[英]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.