尝试使用 json 来使用 mysql、php 和 jquery 填充我的网站区域

发布于 2024-10-09 13:06:28 字数 4093 浏览 3 评论 0原文

好的,这是我第一次尝试使用 JSON 做任何事情。我用 PHP 和 MySql 以及 jQuery 和 JavaScript 做了很多工作……但对 JSON 却一无所获。我在 MySql 数据库中有一些数据。在下面的代码中,我使用 PHP 文件从 MySql 数据库检索数据,并使用 json_encode 将其格式化为 JSON。该文件由页面加载时运行的 JavaScript 调用(实际上,它在 document.ready 上运行)。然后,我使用 jQuery 访问 JSON 键和值以“动态”填充页面区域。这是我正在使用的代码片段(请原谅我在编写这些片段时的“菜鸟”态度,仍在学习所有这些)。

这是我的 HTML 页面上的脚本 test.php

<script type="text/javascript">
$(document).ready(function(){
 $.getJSON("json_events.php",function(data){
  $.each(data.events, function(i,events){
   var tblRow =
    "<tr>"
    +"<td>" + events.id + "</td>"
    +"<td>" + events.customerId + "</td>"
    +"<td>" + events.filingName + "</td>"
    +"<td>" + events.title + "</td>"
    +"<td>" + events.details + "</td>"
     +"<td>" + events.dateEvent + "</td>"
    +"<td><a href='assets/customers/testchurch/events/" + events.image + "'>" + events.image + "</a></td>"
    +"<td>" + events.dateStart + "</td>"
    +"<td>" + events.dateEnd + "</td>"
    +"</tr>"
   $(tblRow).appendTo("#eventsdata tbody");
  });
 });

    $.getJSON("json_events.php",function(data){
     $.each(data.events, function(i,events){
      $("#title").html("First event title: " + events.title + " ...");
     });
    });
});
</script>

这是上述 JS 调用的 php 文件的代码: json_events.php

<?php
require_once('includes/configread.php');

$arrayEvents = array();
$resultsEvents = mysql_query("SELECT * FROM events");

while($objectEvents = mysql_fetch_object($resultsEvents)) {
 $arrayEvents[] = $objectEvents;
}

$json_object_events = json_encode($arrayEvents);
$json_events = "{\"events\": " . $json_object_events . " }";

echo $json_events;

require_once('includes/closeconnread.php');
?>

这是我的 JSON,保存在我的 php 文件 json_events.php 的变量 $json_events 中:

{
    "events": [
        {
            "id": "2",
            "customerId": "1004",
            "filingName": "testchurch",
            "title": "Kenya 2011 Training Meeting",
            "details": "This meeting will be taking place on Sunday, February 10th @ 6pm.  Get ready for our annual Kenya trip in 2011.  We have been blessed to be able to take this trip for the past 3 years.  Now, it's your turn to bless others!  Come to this training meeting to learn how to minister to the people in Kenya and also learn what we'll be doing there.",
            "dateEvent": "2011-02-10",
            "image": "kenya2011.jpg",
            "dateStart": "2010-09-04",
            "dateEnd": "2011-02-10"
        },
        {
            "id": "6",
            "customerId": "1004",
            "filingName": "testchurch",
            "title": "New Series: The Journey",
            "details": "We will be starting our new series titled "The Journey".  Come worship with us as we walk with Paul on his 2nd missionary journey.",
            "dateEvent": "2011-01-02",
            "image": "",
            "dateStart": "2010-09-06",
            "dateEnd": "2011-01-02"
        }
    ]
}

这是我在 test.php 上的 HTML:

<table id="eventsdata" border="1">
    <thead>
        <tr>
            <th>id</th>
            <th>customerId</th>
            <th>filingName</th>
            <th>title</th>
            <th>details</th>
            <th>dateEvent</th>
            <th>image</th>
            <th>dateStart</th>
            <th>dateEnd</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>
<div id="title"></div>

我确实有两个问题...

问题 1:
这段代码乍一看是否写得正确?

问题2:
我希望能够仅从 JSON 数组中的 first 事件中选择标题。我现在使用的代码似乎默认选择第二个事件的标题。我怎样才能做到这一点?

Ok, so this is my first attempt at doing anything with JSON. I have done a lot with PHP and MySql as well as jQuery and JavaScript...but nothing with JSON. I have some data in a MySql database. In the codes below i am using a PHP file to retrieve the data from the MySql database and using json_encode to format it to JSON. This file is being called by the JavaScript that runs when the page loads (well, it runs on document.ready actually). I then use jQuery to access the JSON keys and values to fill in areas of the page "dynamically". Here is the code snippets i am using (excuse my "noobness" on writing these snippets, still learning all this).

This is my script that is on my HTML page test.php:

<script type="text/javascript">
$(document).ready(function(){
 $.getJSON("json_events.php",function(data){
  $.each(data.events, function(i,events){
   var tblRow =
    "<tr>"
    +"<td>" + events.id + "</td>"
    +"<td>" + events.customerId + "</td>"
    +"<td>" + events.filingName + "</td>"
    +"<td>" + events.title + "</td>"
    +"<td>" + events.details + "</td>"
     +"<td>" + events.dateEvent + "</td>"
    +"<td><a href='assets/customers/testchurch/events/" + events.image + "'>" + events.image + "</a></td>"
    +"<td>" + events.dateStart + "</td>"
    +"<td>" + events.dateEnd + "</td>"
    +"</tr>"
   $(tblRow).appendTo("#eventsdata tbody");
  });
 });

    $.getJSON("json_events.php",function(data){
     $.each(data.events, function(i,events){
      $("#title").html("First event title: " + events.title + " ...");
     });
    });
});
</script>

This is the code for the php file being called by the above JS: json_events.php

<?php
require_once('includes/configread.php');

$arrayEvents = array();
$resultsEvents = mysql_query("SELECT * FROM events");

while($objectEvents = mysql_fetch_object($resultsEvents)) {
 $arrayEvents[] = $objectEvents;
}

$json_object_events = json_encode($arrayEvents);
$json_events = "{\"events\": " . $json_object_events . " }";

echo $json_events;

require_once('includes/closeconnread.php');
?>

This is my JSON that is held in the variable $json_events from my php file json_events.php:

{
    "events": [
        {
            "id": "2",
            "customerId": "1004",
            "filingName": "testchurch",
            "title": "Kenya 2011 Training Meeting",
            "details": "This meeting will be taking place on Sunday, February 10th @ 6pm.  Get ready for our annual Kenya trip in 2011.  We have been blessed to be able to take this trip for the past 3 years.  Now, it's your turn to bless others!  Come to this training meeting to learn how to minister to the people in Kenya and also learn what we'll be doing there.",
            "dateEvent": "2011-02-10",
            "image": "kenya2011.jpg",
            "dateStart": "2010-09-04",
            "dateEnd": "2011-02-10"
        },
        {
            "id": "6",
            "customerId": "1004",
            "filingName": "testchurch",
            "title": "New Series: The Journey",
            "details": "We will be starting our new series titled "The Journey".  Come worship with us as we walk with Paul on his 2nd missionary journey.",
            "dateEvent": "2011-01-02",
            "image": "",
            "dateStart": "2010-09-06",
            "dateEnd": "2011-01-02"
        }
    ]
}

This is my HTML on test.php:

<table id="eventsdata" border="1">
    <thead>
        <tr>
            <th>id</th>
            <th>customerId</th>
            <th>filingName</th>
            <th>title</th>
            <th>details</th>
            <th>dateEvent</th>
            <th>image</th>
            <th>dateStart</th>
            <th>dateEnd</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>
<div id="title"></div>

I have two questions really...

Question 1:
Does this code look like it is written correctly at first glance?

Question 2:
I want to be able to select only the title from the first event in the JSON array. The code i am using now is selecting the second events' title by default it seems. How can i accomplish this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

万水千山粽是情ミ 2024-10-16 13:06:28

我要更改的第一件事是您调用 $.getJSON("json_events.php"... 两次。您应该只调用它一次,因为数据不应在调用之间更改。您可以将两个调用连接在一起,但是...

因为您实际上只想要第一个事件标题作为此块的结果:

$.getJSON("json_events.php",function(data){
    $.each(data.events, function(i,events){
        $("#title").html("First event title: " + events.title + " ...");
    });
});

您真正需要的只是将其添加到您的第一个 $.getJSON 调用中并获取去掉上面的块:

$("#title").html("First event title: " + data.events[0].title + " ...");

您可以在这之后添加它:

    $(tblRow).appendTo("#eventsdata tbody");
});

要显示第二个事件标题的问题,并将值设置为最后一个。


这也可以解决为什么 of 正在转义 JSON 响应中的无效字符。其中一个 details 字段中包含引号,这会弄乱数据。

The first thing I would change is that you are calling $.getJSON("json_events.php"... twice. You should only call it once because the data shouldn't change between calls. You could join the two calls together, but...

Since you only really want the first event title as a result of this block:

$.getJSON("json_events.php",function(data){
    $.each(data.events, function(i,events){
        $("#title").html("First event title: " + events.title + " ...");
    });
});

All you really need is to add this to your first $.getJSON call and get rid of the above block:

$("#title").html("First event title: " + data.events[0].title + " ...");

You can add that right after this:

    $(tblRow).appendTo("#eventsdata tbody");
});

This would also solve the problem of why you are showing the second event title. You were iterating through all titles and setting the value to the last one.


Another thing to be careful of is escaping invalid characters in your JSON response. One of the details fields has quotes in it, which would mess up the data.

江湖正好 2024-10-16 13:06:28

我的第一个建议是,不要使用串联来构建表行,而是使用以下方法。

$("<tr></tr>").append($("<td></td>").html(events.id)); 

等等。这样做的原因是您将使用 jQuery 来防止最新、最严重的 XSS 攻击。否则,如果 event.details 包含恶意 JavaScript 代码,您就会被淘汰。

My first recommendation is that instead of using concatenation to build your table rows use the following approach instead.

$("<tr></tr>").append($("<td></td>").html(events.id)); 

etc. The reason for this is that you'll be using jQuery to prevent the latest and greatest in XSS attacks. Otherwise if event.details contains malicious javascript code you're hosed.

疾风者 2024-10-16 13:06:28

问题1:乍一看还不错,良好的开端。

编辑虽然我会查看 json_encode 的 $options参数。除非这只是复制粘贴的受害者,否则第二个条目中的那些引号会给您带来麻烦。 (请参阅 PHP 手册中的示例)

问题 2:如果您查看从 $.each 传递的参数,您将看到 i 参数是迭代器计数,您应该能够管理使用每个块内的比较来分隔第一个元素。

Question1: Seems decent at first glace, good start.

EDIT Though i would look in to json_encode's $options parameter. unless this is just a victim of copy-paste, those quotes in the second entry are going to get you in trouble. (see the examples in the PHP manual)

Question2: If you take a look at the parameters passed from $.each, you'll see the i argument is an iterator count, you should be able to manage separating the first element using a comparison within the each block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文