This article describes how to use ajax to receive json data in ThinkPHP, including the front-end js code and corresponding PHP processing code, which is of great practical value, for more information about how to use ajax to receive json data in ThinkPHP, see the following example. Share it with you for your reference. The specific analysis is as follows:
Here, we use ThinkPHP + jquery to implement ajax. with the extension, we wrote a query. the front-end code is as follows:
First, introduce jquery. js. the main code is as follows:
The code is as follows:
Function ajax (id, pic ){
// Because ThinkPHP does not parse the ThinkPHP constant in JavaScript, it must be defined here first.
Var URL = '/index. php/article ';
$. Ajax ({
Url: URL + '/returnAjax/id/' + id, // URL of the submitted access
Type: 'GET', // method of submission
DataType: 'text', // type of the returned content. because the php file is directly echo, text is used here.
Timeout: 1000, // timeout
Error: function () {// if an error occurs, run the function
Alert ('error loading XML document ');
},
Success: function (data ){
// Alert (data); // if successful, the data is displayed.
WriteHtml (data, pic );
}
});
}
Function writeHtml (data, pic ){
Var product = eval ('+ data +'); // json objects can be converted even if json. js is not introduced.
// Alert ($ ("# cate_pic"). attr ("src "));
$ ("# Cate_pic"). attr ("src", "../images/" + pic );
$ ("# Product_pic"). attr ("src", ".../Attachments/product/" + product. attachpath + "/" + product. attachthumb );
$ ("# Product_subject" example .html (product. subject );
$ ("# Product_content" pai.html (product. content );
}
Echo output is used in Product. class. php. the json_encode () method in thinkphp can automatically convert the object to json format.
The code is as follows:
Public function returnAjax (){
$ Id = $ _ GET ['id'];
$ Product = D ('product')-> where ('Id = '. $ id)-> find ();
// Return a data set in json format
Echo json_encode ($ Product );
// Print_r (json_encode ($ Product ));
}
The returned data format is as follows:
The code is as follows:
{
"Id": "9 ",
"Userid": "1 ",
"Cid": "10 ",
"Cid": "10 ",
"Subject": "1111 ",
"Color ":"",
"Spec ":"",
"Size ":"",
"Keywords ":"",
"Content ":"
1111
",
"Meno": "1111 ",
"Attachpath": "200903 ",
"Attachment": "49d1d86e68d31.png ",
"Attachthumb": "49d1d86e68d31_thumb.png"
}