I have search the net many times and a lot of the JSON tutorials are too hard to understand. I am looking for JSON with jQuery and PHP. if anyone knows any videos or website i can look at that would be great
我在网上搜索了很多次,很多JSON教程都很难理解。我正在使用jQuery和PHP寻找JSON。如果有人知道任何视频或网站,我可以看,那将是伟大的
Thanks
谢谢
3 个解决方案
#1
10
What is JSON and how do I create JSON objects?
The only thing you should know is that JSON is actually Javascript code. You can create arrays and objects with values like strings and numbers (and arrays and objects again)
唯一需要知道的是JSON实际上是Javascript代码。您可以创建具有字符串和数字(以及数组和对象)等值的数组和对象
-
You can store a lot of values in an array, seperated by a comma, like this:
您可以在一个数组中存储许多值,用逗号分隔,如下所示:
[12, "string", -30] // This is an array with 3 values
[12, "string", -30] //这是一个有3个值的数组
-
You can store a lot of values seperated by commas in an object too, WITH your own key, like this:
您也可以使用自己的密钥在对象中存储许多由逗号分隔的值,如下所示:
{"key1": "value1", "key2": 234} // This is an object with two pair of keys and values
{“key1”:“value1”,“key2”:234}//这是一个有两个键和值的对象。
The fun thing is that you can use arrays and objects as values. So, when you put everything you learned above together, you can get JSON code like this:
有趣的是,可以使用数组和对象作为值。所以,当你把上面学到的所有东西放在一起时,你可以得到如下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
]
}
How can I use JSON?
You can use JSON as a simple way to transfer data between the server and the client, like the Twitter API does, for example.
您可以使用JSON作为在服务器和客户端之间传输数据的简单方式,例如,使用Twitter API。
On the client side you can send and receive JSON data via Javascript and AJAX. Often people use jQuery as a library for this, because it has some build in JSON-validation stuff. On the server side you can use PHP for the job to convert the JSON data to a PHP object.
在客户端,可以通过Javascript和AJAX发送和接收JSON数据。人们经常使用jQuery作为库,因为它在json验证中有一些构建。在服务器端,可以使用PHP将JSON数据转换为PHP对象。
You can access values this way in Javascript:
可以用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'
Let me give you an example in which you'll open the flickr stream:
我举个例子,打开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');
}
);
In PHP you can do almost the same:
在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 . '" />';
Example: transfer data between client and server
You can use AJAX, as I said, to send data between the server and the client. Let me give you some simple example... You send something to the server, server sends something back.
如我所说,您可以使用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 file (it's very unsafe this way, but it's a simple example)
PHP文件(这种方式非常不安全,但这是一个简单的示例)
<?php
// A GET request was send, so you can use $_GET
echo '{
"messageFromServer": "Hi back, ' . $_GET['name'] . '"
}';
?>
#2
1
Not specifically json+php, but: Douglas Crockford - The JSON Saga
不是特别json+php,而是:Douglas Crockford——json传奇。
#3
1
All you need is to understand that JSON is data in a different format. You can easily convert a PHP data structure into JSON (json_encode()), and parse a JSON string (json_decode()).
您只需要理解JSON是不同格式的数据。您可以轻松地将PHP数据结构转换为JSON (json_encode())),并解析JSON字符串(json_decode())。
Check the PHP documentation for JSON (linked above) and the jQuery docs for $.ajax().
检查JSON的PHP文档(链接在上面)和$.ajax()的jQuery文档。
Ok, there comes an example.
这里有个例子。
The JavaScript:
JavaScript:
$.ajax({
url: 'json.php',
success: function(data) {
var ul = $('<ul></ul>');
for(var i in data) {
ul.append($('<li></li>')
.append($('<strong></strong>').html(i))
.append(': ')
.append($('<span></span>').html(data[i]))
);
}
$('body').append(ul);
}
});
The PHP file:
PHP文件:
<?php
$dbh = new PDO($connectionstring, $username, $password);
$response = array();
foreach($dbh->query('SELECT id, title FROM table ORDER BY id') as $record) {
$response[$record['id']] = $record['title'];
}
print json_encode($response);
When The jQuery code runs, it requests data from the PHP file. The PHP file gets some content and print it as a JSON code. The response returns, the jQuery parses the JSON into data and fires the callback function.
当jQuery代码运行时,它从PHP文件请求数据。PHP文件获取一些内容并将其打印为JSON代码。响应返回,jQuery将JSON解析为数据并触发回调函数。
#1
10
What is JSON and how do I create JSON objects?
The only thing you should know is that JSON is actually Javascript code. You can create arrays and objects with values like strings and numbers (and arrays and objects again)
唯一需要知道的是JSON实际上是Javascript代码。您可以创建具有字符串和数字(以及数组和对象)等值的数组和对象
-
You can store a lot of values in an array, seperated by a comma, like this:
您可以在一个数组中存储许多值,用逗号分隔,如下所示:
[12, "string", -30] // This is an array with 3 values
[12, "string", -30] //这是一个有3个值的数组
-
You can store a lot of values seperated by commas in an object too, WITH your own key, like this:
您也可以使用自己的密钥在对象中存储许多由逗号分隔的值,如下所示:
{"key1": "value1", "key2": 234} // This is an object with two pair of keys and values
{“key1”:“value1”,“key2”:234}//这是一个有两个键和值的对象。
The fun thing is that you can use arrays and objects as values. So, when you put everything you learned above together, you can get JSON code like this:
有趣的是,可以使用数组和对象作为值。所以,当你把上面学到的所有东西放在一起时,你可以得到如下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
]
}
How can I use JSON?
You can use JSON as a simple way to transfer data between the server and the client, like the Twitter API does, for example.
您可以使用JSON作为在服务器和客户端之间传输数据的简单方式,例如,使用Twitter API。
On the client side you can send and receive JSON data via Javascript and AJAX. Often people use jQuery as a library for this, because it has some build in JSON-validation stuff. On the server side you can use PHP for the job to convert the JSON data to a PHP object.
在客户端,可以通过Javascript和AJAX发送和接收JSON数据。人们经常使用jQuery作为库,因为它在json验证中有一些构建。在服务器端,可以使用PHP将JSON数据转换为PHP对象。
You can access values this way in Javascript:
可以用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'
Let me give you an example in which you'll open the flickr stream:
我举个例子,打开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');
}
);
In PHP you can do almost the same:
在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 . '" />';
Example: transfer data between client and server
You can use AJAX, as I said, to send data between the server and the client. Let me give you some simple example... You send something to the server, server sends something back.
如我所说,您可以使用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 file (it's very unsafe this way, but it's a simple example)
PHP文件(这种方式非常不安全,但这是一个简单的示例)
<?php
// A GET request was send, so you can use $_GET
echo '{
"messageFromServer": "Hi back, ' . $_GET['name'] . '"
}';
?>
#2
1
Not specifically json+php, but: Douglas Crockford - The JSON Saga
不是特别json+php,而是:Douglas Crockford——json传奇。
#3
1
All you need is to understand that JSON is data in a different format. You can easily convert a PHP data structure into JSON (json_encode()), and parse a JSON string (json_decode()).
您只需要理解JSON是不同格式的数据。您可以轻松地将PHP数据结构转换为JSON (json_encode())),并解析JSON字符串(json_decode())。
Check the PHP documentation for JSON (linked above) and the jQuery docs for $.ajax().
检查JSON的PHP文档(链接在上面)和$.ajax()的jQuery文档。
Ok, there comes an example.
这里有个例子。
The JavaScript:
JavaScript:
$.ajax({
url: 'json.php',
success: function(data) {
var ul = $('<ul></ul>');
for(var i in data) {
ul.append($('<li></li>')
.append($('<strong></strong>').html(i))
.append(': ')
.append($('<span></span>').html(data[i]))
);
}
$('body').append(ul);
}
});
The PHP file:
PHP文件:
<?php
$dbh = new PDO($connectionstring, $username, $password);
$response = array();
foreach($dbh->query('SELECT id, title FROM table ORDER BY id') as $record) {
$response[$record['id']] = $record['title'];
}
print json_encode($response);
When The jQuery code runs, it requests data from the PHP file. The PHP file gets some content and print it as a JSON code. The response returns, the jQuery parses the JSON into data and fires the callback function.
当jQuery代码运行时,它从PHP文件请求数据。PHP文件获取一些内容并将其打印为JSON代码。响应返回,jQuery将JSON解析为数据并触发回调函数。