JavaScript botton,从URL解析JSON文件不起作用



我正在尝试显示我从带有按钮的 url 获得的 json 文件中的文本,这就是我现在拥有的:

<p id="text">Show Text Here</p>
<button class="button">Article 1</button>
<script src="jquery/jquery-2.1.4.min.js">
$("button").click(function(){
$.getJSON("http://localhost:3001/api/reading", function(data, status){
var obj=JSON.parse(data);
document.getElementById("text").innerHTML =obj;
console.log(obj);
});
});
</script>

并且通过执行以下操作发送了 json 文件:

app.get('/api/reading', function(req, res){
result = {}
var file_path = path.join(__dirname,'Readings/1.txt');
fs.readFile(file_path, "utf8", function(err, data) {
if(err){
result['err'] = true;
}else{
result['text'] = data;
}
res.json(result);
});
});

但是按钮不起作用,关于如何解决它的任何建议?

首先,正确使用关闭标记</script>

<p id="text">Show Text Here</p>
<button class="button">Article 1</button>
<script src="jquery/jquery-2.1.4.min.js"></script>

然后我建议使用所有jQuery,因为你只包含jQuery,为什么不呢。

$("button").click(function(){
$.getJSON("http://localhost:3001/api/reading", function(data, status){
$("#text").text(JSON.stringify(data));
});
});

API 返回JSON响应,因此data类型为object,因此您需要将对象转换为字符串,然后分配

$("button").click(function() {
$.getJSON("http://localhost:3001/api/reading", function(data, status) {
//as data is already object you need to convert it to text
document.getElementById("text").innerHTML = JSON.stringify(data);
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<p id="text">Show Text Here</p>
<button class="button">Article 1</button>

将控制台.log放在单击函数中或在调试器中单步执行将显示按钮确实响应单击。

看起来您确实试图将 JSON 分配给字符串而不对其进行解析。您是否收到任何控制台错误?

要检查 $.getJson 是否在请求中给出错误,请添加如下.fail()以查看问题所在:

$.getJSON("http://localhost:3001/api/reading", function(data, status){
var obj=JSON.parse(data);
document.getElementById("text").innerHTML =obj;
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});

最新更新