Sending data in JSON format using JavaScript and jQuery
V Past articles, I talked and examples of the receipt and processing of data in JSON format to the client side. But the example of sending data server in this format was not. Today I will try to fix this upuschenie. Prezhde just briefly recall the principle of data in JSON format from the server brauzeru. 1) Server (PHP) script creates an array with the data, converts them into a format JSON (function json encode) and sends brauzeru. 2) On the side of the browser JS script processes the data received. This data is used to convert the eval. To have all data conversion is the use of two funktsiy. Otpravka data server a little slozhnee. Prezhde all, it should be clearly understood that send data in JSON format can be in the parameters of the request (GET or POST), ie . just like any other dannye. T.k. JSON format is a common line, the algorithm will send sleduyuschim. 1) We form JavaScript object with the data you want to send, for example, the values entered by the user in the field formy. 2) Converts this object to JSON format. 3) sends a query server . InOne of the parameters of the query string to pass JSON dannymi. 4) On the server side read transmitted data (they come in the array $ GET or $ POST). 5) Using json decode transform JSON data into massiv. Teper discuss a primer. Dopustim, we there is a page with a form that contains 2 fields: field1 and field2. You'll need to send the data in JSON format, the server script and read it otvet. Razmetku shape, I will not lead, it is normal and in the end of the article, I will link to the archive primerom. Srazu turn to JavaScript kodu. $ (function () ( ?? $ ( "abotchik returns false (line 15). Thus, we can prevent sending data form the usual sposobom. V lines 3-6 we make JavaScript object and fill its introduction in the form dannymi. Zatem send AJAX request (line 7). As the title indicates url parameter PHP script, which performs data processing. In the parameter type – method dannyh. Trety parameter (data) very interesting. Enter here the name of the parameter, which will be sent to the data (jsonData), and the data itself (transform JavaScript object in JSON string using the $. ToJSON). Posle, The success parameter set function which will process received dannye. V result of the server will sent only one parametr jsonData ( "field1": "111", "field2": "222") Teper look at the server skript. Ya decided to make it simple, ie down all possible proverki. Chtenie and data conversion is done one line of code (line 2). As a result, we get an array ($ data) with data formy. Posle This script creates a string that contains the same data and sends it back brauzeru. Kak see an example prostoy. Esli want to get quite a?? experimenting with this model Download arhiv. A If you have any questions – write them in comments
Posted: June 26th, 2009 under Uncategorized.