iT邦幫忙

0

HTML跟XML之間如何傳遞JSON檔案?

本人程序員新手,
最近才上手試作Server和HTML之間的聯動>"<
想試試在不重整網頁的情況下更新介面
想問問有關return資料的問題
想知道如何有效的把html的資料打包成data再到jquery拆包,再由xml打包返回資料到html拆包
ERROR 說由 xml return 的data 不是json格式
"Uncaught SyntaxError: Unexpected token u in JSON at position 0"
由於本人初次接觸>"<沒太多的相關知識和除錯能力
這個問題應該很基本,還請希望大大們多多見諒>"<
HTML:

<script>
		function ShowSomething() {
			var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    var myObj = JSON.parse(this.responseText);
                    document.getElementById("debug").innerHTML = myObj.name;
                }
            };
            xmlhttp.open("GET", "test.php", true);
            xmlhttp.send();
		}

	</script>

PHP:

<?php
$con = mysqli_connect('localhost','xxx','xxx','mydb');
if (!$con) {
  die('Could not connect: ' . mysqli_error($con));
}

$myArr = '{"name":"John", "age":30, "city":"New York"}';
echo json_encode($myArr,true);
mysqli_close($con);
?>
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
japhenchen
iT邦超人 1 級 ‧ 2021-07-08 07:33:49

php的資料應該是這樣寫

<?php
$con = mysqli_connect('localhost','xxx','xxx','mydb');
if (!$con) {
  die('Could not connect: ' . mysqli_error($con));
}
// 你的mysqli 幹嘛用的?
$myArr = array();
$myArr]"name"]="John";
$myArr["age"] = 30;
$myArr["city"] = "New York";

echo json_encode($myArr,true);
mysqli_close($con);
// 回應完避免有多餘的HTML被回傳,盡量在這做die()跟exit()
?>
看更多先前的回應...收起先前的回應...

既然都用jQuery了,何不用到底,自己寫底層的XMLHttpRequest對入門真的很累....(雖然是必要的)

$.post({
    url: "test.php",
    dataType : "json",
    data:{
        customid: "0001"
    }
})
    .done(function(jsondata){
        //jsondata來自於PHP echo的json,會自動parse
       jsondata.forEach(function(idx,val){
           console.log(index,val); // 自己看著變
       }
    });
gaia2222 iT邦新手 5 級 ‧ 2021-07-08 19:32:52 檢舉

非常感謝大大的建議>"<,上面的只是一個我簡化的例子,是會有資料從sql之中取出來的XD我只是把他簡化一下

非常感謝你提供的資訊,只是剛開始想把php/html之間的資料做交換就發生問題,所以先從簡單的做起,之後我會認真研究一下自己寫底層的XMLHttpRequest,謝謝你0 w0b

gaia2222 iT邦新手 5 級 ‧ 2021-07-08 20:08:16 檢舉

不好意思多問一句>"<不知為什麼還會有ERROR,JSON.parse不能識別this.responseText是json object

responseText = {"name":"Samson","age":30}

HTML:

<script>
		function ShowSomething() {
			var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                     document.getElementById("debug").innerHTML = this.responseText;
                    const myObj = JSON.parse(this.responseText);
                }
            };
            xmlhttp.open("GET", "Test.php", true);
            xmlhttp.send();
		}

	</script>

PHP:

<?php
    $myArr = array();
$myArr["name"]="Samson";
$myArr["age"] = 30;
    echo json_encode($myArr,true);

?>

你在javascript上把fail的內容log一下,貼在這裡看看

gaia2222 iT邦新手 5 級 ‧ 2021-07-09 18:30:42 檢舉

抱歉>"<原來是我搞錯了,原來php檔有了,, JSON檔就認至出來,現在可以了0 w0/感謝大大幫忙

我要發表回答

立即登入回答