This article describes how ThinkPHP implements the ajax search function on the official website. The example demonstrates the background query function and the method of submitting search data by Ajax at the front end. It is a very practical technique, for more information about how to use ThinkPHP to search for ajax on the official website, see the examples in this article. Share it with you for your reference.
The specific implementation method is as follows:
Background code:
The Code is as follows:
// Search. If the value of 1 is not 0
Function search (){
$ Keyword = $ _ POST ['search'];
$ Goods = M ('goods ');
// Here I make a fuzzy query to the name or corresponding id, mainly because my system is
// Directly view the product ID in the mall System
$ Map ['goods _ id | goods_name '] = array ('like',' % '. $ keyword.' % ');
// Pass the query condition into the query method
If ($ goods = $ Goods-> where ($ map)-> select ())
{
$ This-> ajaxReturn ($ goods, 'query successful! ', 1 );
} Else {
$ This-> ajaxReturn ($ data, "query failed, data does not exist! ", 0 );
}
}
Front-end code:
The Code is as follows:
$ (Document). ready (function (){
$ (". Show_message"). hide ();
Var $ search = $ ('# search_box ');
$ ("# Submit_from"). click (function (){
If ($ ("# search_box"). attr ("value") = '')
{
// Alert ('enter the text! ');
$ (". Show_message" cmd.html ('error message: the text in the search box cannot be blank! ');
$ (". Show_message"). fadeIn (1000 );
$ (". Show_message"). fadeOut (1000 );
$ Search. focus ();
// Return false;
} Else {
// Start ajax execution data
$. Ajax ({
Type: "POST ",
Url: "/index. php/Goods/search ",
Data :{
Search: $ search. val ()
},
DataType: "json ",
Success: function (data ){
If (data. status = 1 ){
// Alert (data.info );
Var html = '';
$. Each (data. data, function (no, items ){
Html + = '';
});
Html + ="
'+ Items. goods_id + ''+ items. goods_name +'' + items. add_time + ''+ items. brand +'' + items. price + '";
$ (". Goods-list" ).html ('your .html (html );
// Alert (html );
}
Else if (data. status = 0 ){
$ (". Show_message"). show ();
$ (". Show_message" pai.html (data.info );
$ (". Show_message"). fadeOut (3000 );
// Alert (data.info );
Return false;
}
}
});
}
});
});
I hope this article will help you with ThinkPHP framework programming.