PHP如何返回json格式的数据给jquery
json格式的数据是我们在应用开发中一直会使用到的数据,如与jquery打交到或与api打交都会使用到json数据,那么PHP如何返回json格式的数据给jquery呢,下面我来给各位同学介绍介绍.
在jquery中操作json数据我们直接 $.parseJSON(returnString ) 了
实例代码如下:
$(function () { $('#send').click(function () { $.getJSON('test.js', function (data) { $('#resText').emptyempty(); var html = ''; $.each(data, function (commentIndex, comment) { html += '<div class="comment"><h6 id="nbsp-nbsp-comment-username-nbsp-nbsp">' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>'; }) $('#resText').html(html); }) }) })
你需要做的就是将数据存储为格式正确的 .json或者.js 文件.以下为示例所传送的json格式的数据
实例代码如下:
[ { "username": "张三", "content": "沙发." }, { "username": "李四", "content": "板凳." }, { "username": "王五", "content": "地板." } ]
上面讲到到的json数据是固定了,我们用php如何返回json数据呢
php输出JSON格式方法
页面中加入header('Content-type: text/json');这个头就是告知此文件输出类型为 json,这种形式我们见的最多的是验证码——php输出验证图片,有时php可以输出css文件,js文件等做一些有趣的事情.好的,我们测试一下吧
实例代码如下:
<?php header('Content-type: text/json'); $fruits = array ( "fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"), "numbers" => array(1, 2, 3, 4, 5, 6), "holes" => array("first", 5 => "second", "third") ); echo json_encode($fruits); ?>
从数据库读取的数据生成json格式
实例代码如下:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>第一php网提供的教程--将数据库读取的数据生成json格式</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://libs.useso.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"/></script> <script language=javascript> </script> </head> <body> <pre class="brush:php;toolbar:false"> <h1 id="请注意两种方法生成的对象数组在结构上的区别">请注意两种方法生成的对象数组在结构上的区别</h1> <?php echo '<h1 id="法一">法一</h1>'; //假设以下数组是根据我们从数据库读取的数据生成的 $jarr=array('total'=>239,'row'=>array( array('code'=>'001','name'=>'中国','addr'=>'Address 11','col4'=>'col4 data'), array('code'=>'002','name'=>'Name 2','addr'=>'Address 12','col4'=>'col4 data'), ) ); //法一: $jobj=new stdclass();//实例化stdclass,这是php内置的空类,可以用来传递数据,由于json_decode后的数据是以对象数组的形式存放的, //所以我们生成的时候也要把数据存储在对象中 foreach($jarr as $key=>$value){ $jobj->$key=$value; } print_r($jobj);//打印传递属性后的对象 echo '使用$jobj->row[0]['code']输出数组元素:'.$jobj->row[0]['code'].'<br>'; echo '编码后的json字符串:'.json_encode($jobj).'<br>';//打印编码后的json字符串 //法二: echo '<hr>'; echo '<h1 id="法二">法二</h1>'; echo '编码后的json字符串:'; echo $str=json_encode($jarr);//将数组进行json编码 echo '<br>'; $arr=json_decode($str);//再进行json解码 print_r($arr);//打印解码后的数组,数据存储在对象数组中 echo '使用$arr->row[0]->code输出数组元素:'.$arr->row[0]->code; ?> </body> </html>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. When writing programs in Golang, we often need to convert the structure into a JSON string. In this process, the json.MarshalIndent function can help us. Implement formatted output. Below we will explain in detail how to use this function and provide specific code examples. First, let's create a structure containing some data. The following is an indication

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Using PHP's json_encode() function to convert an array or object into a JSON string and format the output can make it easier to transfer and exchange data between different platforms and languages. This article will introduce the basic usage of the json_encode() function and how to format and output a JSON string. 1. Basic usage of json_encode() function The basic syntax of json_encode() function is as follows: stringjson_encod

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas
