<分区>
我在网上搜索了很多次,很多JSON教程太难理解了。我正在寻找带有 jQuery 和 PHP 的 JSON。如果有人知道我可以看的任何视频或网站,那就太好了
谢谢
<分区>
我在网上搜索了很多次,很多JSON教程太难理解了。我正在寻找带有 jQuery 和 PHP 的 JSON。如果有人知道我可以看的任何视频或网站,那就太好了
谢谢
最佳答案
您唯一应该知道的是 JSON 实际上是 Javascript 代码。您可以使用 strings 和 numbers(以及数组和对象)等值创建数组和对象
您可以在数组中存储很多值,用逗号分隔,如下所示:
[12, "string", -30]//这是一个有 3 个值的数组
您也可以在一个对象中存储大量以逗号分隔的值,使用您自己的键,如下所示:
{"key1": "value1", "key2": 234}//这是一个有两对键和值的对象
有趣的是您可以使用数组和对象作为值。所以,当你把上面学到的所有东西放在一起时,你可以得到这样的 JSON 代码:
{ // Creates an object
"key1": 12, // with a key called "key1" and a number as value
"key2": [ // and another key called "key2", with an new array as value
10, // the array has the number ten as first value
"value" // and a string containing "value" as its second value
]
}
您可以使用 JSON 作为在服务器和客户端之间传输数据的简单方法,例如 Twitter API。
在客户端,您可以通过 Javascript 和 AJAX 发送和接收 JSON 数据。通常人们使用 jQuery 作为库,因为它有一些内置的 JSON 验证功能。在服务器端,您可以使用 PHP 将 JSON 数据转换为 PHP 对象。
您可以在 Javascript 中以这种方式访问值:
someArray[0]; // gives you access to the first value of an array
someObject.key; // gives you access to the value of an object with key 'key'
让我举个例子,您将在其中打开 flickr 流:
// $.getJSON(url, dataHandlerFunction); to get JSON-data
// Add the first image of the Flickr stream to the page
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data){
// In this function you can do anything with the JSON code, because it's transformed into a Javascript object
// If you open the above URL in your browser, you see that it exists of and object with
// a key called items. Within is an array of objects, representing images
// let's add the first one to our page
var firstImg = data.items[0]; // First object, with image data.
$("<img/>").attr("src", firstImg.media.m).appendTo('body');
}
);
在 PHP 中,您可以做几乎相同的事情:
// Get the JSON code form Flickr
$contents = file_get_contents('http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?');
// Decode it to a PHP object
$flickrStream = json_decode($contents);
// Display the image
echo '<img src="' . $flickrStream->items[0]->media->m . '" />';
正如我所说,您可以使用 AJAX 在服务器和客户端之间发送数据。让我给你举个简单的例子……你向服务器发送一些东西,服务器返回一些东西。
// Sends a GET request to the server
$.ajax({
url: '/to/your/php/file/',
dataType: 'json',
data: {
"name": "client"
},
success: function(data){
alert(data.messageFromServer); // alerts "Hi back,
}
});
PHP文件(这种方式很不安全,不过是个简单的例子)
<?php
// A GET request was send, so you can use $_GET
echo '{
"messageFromServer": "Hi back, ' . $_GET['name'] . '"
}';
?>
关于php - 我在哪里可以找到关于 JSON 和 PHP 的好视频或教程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3471706/