2017-03-04 113 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; 
相关问题