gpt4 book ai didi

javascript - 如何获取 jQuery.get "Data"中的特定元素

转载 作者:行者123 更新时间:2023-12-02 21:07:20 24 4
gpt4 key购买 nike

所以我有数据(data.html)

$(document).ready(function(){
setTimeout(function(){
$.get("/computers/{{computer.id}}/live", function(data){
console.log(data)
});
}, 5000);
});

问题是“data”是“/computers/{{computer.id}}/live”的整个源代码我想在html中获取特定的id

/computers/{{computer.id}}/live (HTML file):

<script type="text/javascript" src="{{ url_for('static', filename='jquery.js') }}"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<script>
$(document).ready(function(){
setTimeout(function(){
$('#id').load("")
}, "{{timer}}");
});
</script>
<div id="id">
<span class="badge badge-light" id ="cpu">{{computer.cpu_usage_procentage}}</span>
<span class="badge badge-light" id ="memory">{{computer.memory_usage_procentage}}</span>
</div>

如何选择cpu和内存 id和console.log它们的值(当然在data.html中)或更具体地将它们放入 data.html页面

最佳答案

您可以使用 jQuery 默认函数解析 html 来完成此操作:

 var html = `<div id="id">
<span class="badge badge-light" id ="cpu">44%</span>
<span class="badge badge-light" id ="memory">66%</span>
</div>`;
var parsed = $(html);

var cpuUsage = parsed.find("#cpu").text();
var memUsage = parsed.find("#memory").text();
console.log(`CPU usage ${cpuUsage} - Mem usage ${memUsage}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您还可以在服务器中创建 API 以提供 JSON 格式的信息:

/computers/{{computer.id}}/livejson:

{
cpuUsage: "{{computer.cpu_usage_procentage}}",
memUsage: "{{computer.memory_usage_procentage}}"
}

在客户端:

 $.get("/computers/{{computer.id}}/livejson", function(json){
var data = JSON.parse(json);
console.log(`CPU usage ${data.cpuUsage} - Mem usage ${data.memUsage}`);
});

关于javascript - 如何获取 jQuery.get "Data"中的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61192422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com