簡體   English   中英

使用JSON和JQuery解析變量中的數據

[英]Parcing data from a variable using JSON and JQuery

我正在嘗試使用JSON請求變量的值,但JSON代碼出了點問題,我不知道它是什么。 有人可以給我一些小費嗎?

JSON代碼:

{
"counter1": {
        "variable": :="webdata".counter1:
        },
"counter2": {
        "variable": :="webdata".counter2:
        },
}

jQuery代碼:

$(document).ready(function(){
    $.ajaxSetup({ cache: false }); 
setInterval(function() {
    $.getJSON("json_data.json", function(result){
        $('#counter1').text((result.variable[0]).trim());
    $.getJSON("json_data.json", function(result){
        $('#counter1').text((result.variable[0]).trim());
    });
},1000);
});

HTML代碼:

<p label="counter1">0</p>
<p label="counter2">0</p>

提前致謝!

JSON並不是唯一出問題的地方。 為什么在Javascript中兩次調用相同的代碼(稱為jQuery)

並且“ p”元素中的“標簽”屬性是錯誤的,應該為“ id”。

我不確定是什么生成了JSON,但這是實現目標的一種可能方法。

將JSON輸出更改為:

{
"counters": [
    {
        "variable" : "COUNTER 1_VARIABLE"
    },
    {
        "variable" : "COUNTER2_VARIABLE"
    }
]
}

大寫字母應位於變量的大寫位置,因為這是序列化的輸出

jQuery代碼:

$(document).ready(function(){
$.ajaxSetup({ cache: false }); 
setInterval(function() {
$.getJSON("json_data.json", function(result){
$('#counter1').text((result.counters[0].variable).trim());
$.getJSON("json_data.json", function(result){
    $('#counter2').text((result.counters[1].variable).trim());
});
},1000);
});

值得注意的是,文檔中不鼓勵使用“ $ .ajaxSetup()”。 https://api.jquery.com/jquery.ajaxsetup/

HTML代碼:

<p id="counter1">0</p>
<p id="counter2">0</p>

首先,感謝大家的迅速回答。

我設法使JSON工作如下:(盡管我仍然有問題)

JSON代碼(json / json_data.json):

{
    "counters": [
        {
            "variable": ":='webdata'.counter1:"
        },
        {
            "variable": ":='webdata'.counter2:"
        }
    ]
}

jQuery代碼(my_script.js):

$(document).ready(function(){
    $.ajaxSetup({ cache: false }); 
setInterval(function() {
    $.getJSON("json/json_data.json", function(result){
        $('#counter0').text(result.counters[0].variable);
    });
},1000);
});

HTML代碼(index.htm):

<tr>
    <td>PT000</td>
    <td>Process value 0</td>
    <td> <label id="counter0">0</label> </td>
    <td>bar</td>
</tr>

現在,關鍵是要在屏幕上打印以JSON格式編寫的文本,這是我的變量的名稱,可以說是達到我要打印的值的路徑。

關鍵是,如果我使用HTM文件並在其上寫入變量的名稱,然后我僅使用JQuery來獲取其有效的數據,但是我想打印出很多值,因此我認為JSON可以幫助我解決這個問題。 這里是帶有HTM文件的示例:

HTM代碼(IOValue1.htm):

:="webdata".counter1:

jQuery代碼(my_script.js):

$(document).ready(function(){
    $.ajaxSetup({ cache: false }); 
setInterval(function() {
    $.get("IOValue1.htm", function(result){
        $('#counter1').text((result));
    });
},1000);
});

HTML代碼(index.htm):

<tr>
    <td>PT001</td>
    <td>Process value 1</td>
    <td> <label id="counter1">0</label> </td>
    <td>bar</td>
</tr>

可能我沒有考慮JSON的一些基本事實,但是我不太有經驗。 任何想法?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM