Front-end learning 2-in-depth ajax and restful

Source: Internet
Author: User

0. PrefaceSome time ago, I learned RESTFUL along with Yeelink and tried to implement simple REST API using PHP and Slim frameworks. Raspberry Pi can GET JSON data packets through the GET method, in this way, Raspberry Pi interacts with the server (my PC. However, because there is no WEB Front-end, you can only use the cURL tool or directly modify the database to change the LED status, and the experience is very poor. Front-end Framework experience: [frontend Learning 1 -- Bootstrap jquery ajax]For more information about getting started with REST APIs, see: [PHP re-learning 4 -- slim framework learning and use] [PHP re-learning 5 -- RESTFul framework remote control LED] by [Open Source IOT-the smallest IOT system design scheme and source code] impact. I decided that I should do more than the server and embedded side.
1. REST APIUse the PHP Slim framework to construct the rest api. There are two APIs related to this example. One is to obtain all the LED information, which includes the ID, description, and status. The other is to update the LED status, which has only two ON or OFF statuses, indicates opening and closing.[Retrieve all LED information]The HTTP Method gethttp url/api/ledsHTTP is returned, as shown in [description] 1. total indicates the total number of records. Using total is mainly used for paging. rows indicates a specific record. rows is followed by a json array 3. if no page or rows is specified in the URL, the default page is 1 and the rows is 10. simply put, only 10 are returned by default.
Figure 1 GET method to obtain LED information
[Update an LED status]HTTP Method puthttp url/api/leds/<leds_id>/statusHTTP request content {"status": "on"} or {"status ": "off"} HTTP Response {"success": "true"} or {"success": "false "}

Figure 2 PUT request Analysis 2. Update the table[1] Create a table without filling in the content

<Div class = "row"> <div class = "span12"> <table class = "table-hover" id = "ledsTable"> <thead> <tr> <th> ID </th> <th> DESC </th> <th> STATUS </th> <th> ACTION </th> </tr> </ thead> </table> </div>


[2] update a table-ajax Method [JS Code]
Function updateAll () {// dynamic table content $. getJSON ('HTTP: // localhost/api/leds ', function (data) {// data. total indicates the total number of records. // data. row indicates the Record Content console. log (data. total); $. each (data. rows, function (index, item) {// retrieve id description status var id = item. id; console. log (id); var description = item. description; console. log (description); var status = item. status; console. log (status); console. log (status); var btnStyle = 'btn-success '; var btnText; // modify the button style. if ON is green, OFF is white. if (status = 'on ') {btnStyle = 'btn-success '; btnText = 'o n';} else {btnStyle = 'btn-default'; btnText = 'off';} // insert a row, unfortunately, javascript does not have format var newRow = '<tr dev_id = "' + id + '">' + '<td>' + id + '</td>' + '< td> '+ description +' </td> '+' <td> '+ status +' </td> '+' <button type =" button "class =" btn-xs '+ btnStyle +' "> '+ btnText +' </button> '+' </td> '+' </tr>'; $ ('# ledstable '). append (newRow );});});}


[Notes]1. $. getJSON ('HTTP: // localhost/api/leds ', function (data) uses the ajax getJSON method, and the URL is http: // localhost/api/leds; if an HTTP response is obtained, the response content is in data. 2. $. each (data. rows, function (index, item) use the each method to traverse all data. rows content-all LED information, LED information is in item, and index is the serial number (not the same as the led id) 3.var newRow = '<tr dev_id = "' + id + '">' + adds the dev_id attribute to all tr tags, so that you can obtain the number when the LED status changes. 4. $ ('# ledstable'). append (newRow); added to the table.

3. Button Control [Basic process]Press the button at the end of the table, locate the device ID in the tr tag in the button event processing (specifically called callback processing), and find text from the 2nd td tags of the row, the text is the current LED status, and finally a PUT request is assembled to flip the LED status. [JS Code]
$ ("Table "). delegate ("button", "click", function () {console.info ($ (this); // try to get the <button> text </button> console. log ($ (this ). text (); var $ tr_obj = $ (this ). parent (). parent (); // The tr element contains the dev_id attribute var dev_id = $ tr_obj.attr ('dev _ id'); console. log (dev_id); // access all sub-td elements of the tr element var $ td_obj =$ ($ tr_obj ). children ("td"); // The second var $ status_obj of all td elements =$ ($ td_obj ). eq (2); var status_str = $ status_obj.text (); console. log (status_str); // change the button style if (status_str = "on") {$ (this ). removeClass ('btn-success '); $ (this ). addClass ('btn-default'); $ (this ). text ("OFF"); $ status_obj.text ("off"); send_ledctrl (dev_id, "off");} else {$ (this ). removeClass ('btn-default'); $ (this ). addClass ('btn-success '); $ (this ). text ("o n"); $ status_obj.text ("on"); send_ledctrl (dev_id, "on") ;}}; function send_ledctrl (dev_id, cur_status) {$. ajax ({url: '/api/leds/' + dev_id + '/status', // api/leds/1 async: true, dataType: 'json', type: 'put', data: JSON. stringify ({status: cur_status}), success: function (data, textStatus) {// print the returned content {"success": true} console. log (data. success) ;}, error: function (jqXHR, textStatus, errorThrown) {console. log ("error ");},});}


[Notes]1. $ ("table"). delegate ("button", "click", function () {uses the delegate method of table. The subclass is button and the event is click. Delegate can add events for dynamically created tags, different from the on method. 2. var $ tr_obj = $ (this). parent (). parent (); obtain the tr tag and use the subclass to find the parent class. Here $ tr_obj is a jquery object, and $ is added before all objects to mark them. 3. $ (this ). removeClass ('btn-success '); $ (this ). addClass ('btn-default'); Based on the LED status, clear the old style of the BUTTON to obtain the new style.

4. Final Results
Figure 3 final effect

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.