我對JSON並不太滿意,所以請原諒這是否是一個主要的新手錯誤。我向本地文件發送查詢,該文件對外部網站的API執行cURL並返回JSON對象。因爲我必須爲API查詢x查詢,所以我只複製並粘貼了一個,而我正在使用它來替換cURL。我有以下腳本:無法將JSON對象轉換爲任何可用的
$.ajax({
type: 'GET',
url: 'ajax.php?v='+value, //with this being an input value, which is totally irrelevant because I'm not actually doing the cURL query anyway
dataType: 'json',
success:function(json){
var o_response = json;
json = $.parseJSON(json);
alert(o_response.toSource());
alert(json.toSource());
},
error: function (xhr, ajaxOptions, thrownError) {
alert('There appears to be a problem with the information you submitted. Please try again or contact us.');
}
});
而PHP在ajax.php看起來是這樣的:
<?
if (isset($_GET['v']) && $_GET['v'] != '') {
$response = '[{"query":"14-22-25-02-W5","response":{"status":"ok","err":[],"lat":51.152259,"lng":-114.202199,"country":"Canada","province":"AB","city":"Calgary","street":"49 Royal Vista Drive NW","street_prox":78,"address":"49 Royal Vista Drive NW, Calgary, AB","lsd":"14-22-25-2 W5","lsd_border":[[51.150459,-114.199327],[51.150447,-114.205067],[51.154059,-114.205071],[51.154072,-114.199332],[51.150459,-114.199327]],"uwi":"","nts":"","nts_border":[],"utm":"11S 695661E 15670479N","utm_v":"Zone 11, 695661 meters easting, 15670479 meters northing (Southern Hemisphere)"}}]';
echo json_encode($response);
}
?>
隨着$響應是完全一樣什麼API給我。
我想要做的是從中獲取「lat」和「lng」值。我的JavaScript文件中的第一個示例是「alert(o_response.toSource());」位使它成爲一個字符串,這很好,但我想要一個對象。第二個例子「alert(json.toSource());」使其成爲一個對象,但刪除所有鍵周圍的引號。例如,它這樣做:
[{query:"14-22-25-02-W5", response:{status:"ok", err:[], lat:51.152259, lng:-114.202199, country:"Canada", province:"AB", city:"Calgary", street:"49 Royal Vista Drive NW", street_prox:78, address:"49 Royal Vista Drive NW, Calgary, AB", lsd:"14-22-25-2 W5", lsd_border:[[51.150459, -114.199327], [51.150447, -114.205067], [51.154059, -114.205071], [51.154072, -114.199332], [51.150459, -114.199327]], uwi:"", nts:"", nts_border:[], utm:"11S 695661E 15670479N", utm_v:"Zone 11, 695661 meters easting, 15670479 meters northing (Southern Hemisphere)"}}]
注意如何「查詢」,「響應」,「狀態」,「緯度」,「LNG」等,不再有他們周圍的報價。我想這是它應該工作的方式。那麼,如果我嘗試通過執行以下操作來獲得「響應」:
alert(json.response);
alert(json['response']);
alert(json[1]);
我得到的只有3個未定義的提醒。
我明顯錯過了一些東西。它的格式不正確嗎?我解析或編碼的東西,我不應該?
任何幫助將非常感激。
謝謝。
你是JSON編碼一個包含JSON文本的字符串。將其解碼得到JSON的原始字符串。不要這樣做。 – SLaks
爲什麼你在已經使用JSON格式的字符串上使用json_encode?更好的問題:爲什麼你把字符串放在JSON格式中 - 你應該在數組上調用json_encode。 – Barmar
請按照上面的註釋,但注意問題調用你的本地主機(127.0.0.1)的ajax問題,一些瀏覽器沒有配置正確的安全覆蓋將安靜地失敗,不會給出錯誤,只是沒有響應。一個共同的問題。 –