2017-03-04 109 views
0

我怎樣才能解決這個錯誤JSON.parse: unexpected character at line 1 column 2 of the JSON dataJSON.parse:第1行的JSON數據(HTML)的第2列意外的字符

我試圖顯示從股票連接特定的JSON內容,但遺憾的是不能讓它工作,因爲錯誤不斷彈出。

HTML

<input id="currency1" type="text"> 
    <span>Currency1</span> 
    <input id="currency2" type="text"> 
    <span>Currency2</span> 
    <div> 
    <button type="button" onclick="refreshPrice()"> 
    Refresh Price 
    </button> 
    <span id="lastPrice"></span> 
    </div> 

從北京時間鏈接JSON響應

{"ticker":{"high":"16985100","low":"16730900","last":"16879000"}} 

JAVASCRIPT

var lastPrice; 
function refreshPrice() { 
$lastPrice = $('#lastPrice'); 
$lastPrice.html(""); 
$.get("https://example.com") //Ticker link 
.then(function (data) { 
    lastPrice = JSON.parse(data).ticker.last - 100000; 
    lastPrice.html(lastPrice); 
}); 
} 

refreshPrice(); 
$('#currency2').keyup(function() { 
currency2Val = parseFloat($(this).val()); 
if (currency2Val) { 
currency1Val = currency2Val * lastPrice; 
    $('#currency1').val(parseInt(currency1Val)); 
} 
else { 
    $('#currency1').val(""); 
} 
}); 

$('#currency1').keyup(function() { 
currency1Val = parseInt($(this).val()); 
if (currency1Val) { 
currency2Val = currency1Val/lastPrice; 
    $('#currency2').val(currency2Val.toFixed(8)); 
} 
else { 
    $('#currency2').val(""); 
} 
}); 

任何幫助將不勝感激,謝謝

+1

您響應可能是HTML而不是JSON ......或者它已經被解析,並且你正試圖解析一個對象! ...試試'lastPrice = data.ticker.last - 100000;' –

+1

也'lastPrice.html(lastPrice);'如果lastPrice'是一個'Number'(它肯定會是) - 沒有意義 - 我認爲你的意思是'$ lastPrice.html(lastPrice);' –

+0

這是正確的,你對'$ lastPrice.html(lastPrice)'是正確的,它解決了錯誤信息。謝謝 – Julius

回答

0

假設股票代碼響應正確的Content-Type標題,jQuery將已經已經解析了您的響應。所以刪除JSON.parse

$.get("https://example.com") //Ticker link 
.then(function (data) { 
    lastPrice = data.ticker.last - 100000; 
    $lastPrice.html(lastPrice); 
}); 

(我還包含一個固定在那裏the issue Jaromanda X pointed out,使用lastPrice而非$lastPrice

the documentation

dataType(默認:智能猜測(xml,json,script或html))

類型:字符串

您期望從服務器返回的數據類型。 如果沒有指定,jQuery將嘗試根據響應的MIME類型推斷它(XML MIME類型將生成XML,在1.4中JSON將生成一個JavaScript對象,在1.4腳本中將執行該腳本以及其他任何內容將作爲字符串返回)。

1

嘗試刪除JSON.parse,

var lastPrice; 
function refreshPrice() { 
$lastPrice = $('#lastPrice'); 
$lastPrice.html(""); 
$.get("https://example.com") //Ticker link 
.then(function (data) { 
    debugger; 
    lastPrice = data.ticker.last - 100000; 
    lastPrice.html(lastPrice); 
}); 
} 

將一個調試器,以及,看你有什麼反應。

0

響應已經是JSON格式,你不應該將其通過JSON.parse,作爲JSON.parse預計輸入是一個字符串化JSON

試試這個:

lastPrice = data.ticker.last - 100000; 
相關問題