我想要做一個可以從arduino讀取動態數據的網站,不用重新整理就會一直更新,目前得知遇到的問題是datas從getData()方法返回的是字符串類型,但不能用字符串類型要先將它反序列化才行,但我試了好幾次還是一直失敗,所以想請問大家是否有甚麼方法可以幫助我,或是有其他方法可以讀取動態數據放在網站,感謝大家的幫助,謝謝。
view.py
from django.http import JsonResponse
from django.shortcuts import render
def getDatas():
    
    serialPort = "COM4"
    baudRate = 9600
    ser= serial.Serial(serialPort,baudRate,timeout=0.5)
    
    
    while True:  
        ser.write('a'.encode())
        sleep(1)
        ser.write('b'.encode())
        sleep(1)
        
        str =ser.readline().decode() # 获取arduino发送的数据
        if str.strip()!='':
            print(str)
            updata_time=datetime.datetime.now().strftime('')
            print(updata_time)
            return str,updata_time
 
def index(request):
    global i        # 同步全局變量
    i += 1         # 監測按鈕點擊事件
    if i != 1:
         print("已點擊重新整理")
    else:
        print("初載")
 
    datas=getDatas()[0]
    context={
        'data':datas,  
    }
    context = {"data1":datas.objects.order_by("-time")[0].temp1,
        "data2":datas.objects.order_by("-time")[0].temp2}
    context["name"]="量測系統"
    return render(request,"index.html",context) # 通過render模塊把index.html這個文件返回到前端
index.html
<script>
            $(document).ready(function(){
                function refresh(){
                    $.getJSON("/index/", function (ret) {
                        $('#result').html(ret.data1);
                        $('#result2').html(ret.data2);
                    })
                }
                setInterval(refresh, 3000)
            })
        </script>
錯誤呈現
![https://img.onl/2zlNzk]https://img.onl/2zlNzk