HTML در JSON
پرش به ناوبری
پرش به جستجو
JSON میتواند به راحتی به جاوا اسکریپت ترجمه شود. [۱]
جاوا اسکریپت میتواند برای ساخت HTML در صفحههای وب شما استفاده شود.
جدول HTML
ساخت یک جدول HTML با استفاده از دادههای دریافت شده به صورت JSON:
مثال
1 obj = { table: "customers", limit: 20 };
2 dbParam = JSON.stringify(obj);
3 xmlhttp = new XMLHttpRequest();
4 xmlhttp.onreadystatechange = function() {
5 if (this.readyState == 4 && this.status == 200) {
6 myObj = JSON.parse(this.responseText);
7 txt += "<table border='1'>"
8 for (x in myObj) {
9 txt += "<tr><td>" + myObj[x].name + "</td></tr>";
10 }
11 txt += "</table>"
12 document.getElementById("demo").innerHTML = txt;
13 }
14 }
15 xmlhttp.open("POST", "json_demo_db_post.php", true);
16 xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
17 xmlhttp.send("x=" + dbParam);
جدول HTML داینامیک (به فارسی: پویا)
ایجاد یک جدول HTML با توجه به مقدار انتخاب شده در منوی کشویی:
ساخت نمونه مثال این بخش در دست اقدام است.
مثال
1 <select id="myselect" onchange="change_myselect(this.value)">
2 <option value="">Choose an option:</option>
3 <option value="customers">Customers</option>
4 <option value="products">Products</option>
5 <option value="suppliers">Suppliers</option>
6 </select>
7
8 <script>
9 function change_myselect(sel) {
10 var obj, dbParam, xmlhttp, myObj, x, txt = "";
11 obj = { table: sel, limit: 20 };
12 dbParam = JSON.stringify(obj);
13 xmlhttp = new XMLHttpRequest();
14 xmlhttp.onreadystatechange = function() {
15 if (this.readyState == 4 && this.status == 200) {
16 myObj = JSON.parse(this.responseText);
17 txt += "<table border='1'>"
18 for (x in myObj) {
19 txt += "<tr><td>" + myObj[x].name + "</td></tr>";
20 }
21 txt += "</table>"
22 document.getElementById("demo").innerHTML = txt;
23 }
24 };
25 xmlhttp.open("POST", "json_demo_db_post.php", true);
26 xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
27 xmlhttp.send("x=" + dbParam);
28 }
29 </script>
لیست کشویی در HTML
ساخت یک منوی کشویی HTML با اطلاعات دریافتی از سمت سرور به صورت JSON:
مثال
1 <syntaxhighlight lang="">
2 obj = { table: "customers", limit: 20 };
3 dbParam = JSON.stringify(obj);
4 xmlhttp = new XMLHttpRequest();
5 xmlhttp.onreadystatechange = function() {
6 if (this.readyState == 4 && this.status == 200) {
7 myObj = JSON.parse(this.responseText);
8 txt += "<select>"
9 for (x in myObj) {
10 txt += "<option>" + myObj[x].name;
11 }
12 txt += "</select>"
13 document.getElementById("demo").innerHTML = txt;
14 }
15 }
16 xmlhttp.open("POST", "json_demo_db_post.php", true);
17 xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
18 xmlhttp.send("x=" + dbParam);
منابع آموزشی