Ajax makes get and post requests to the server

Source: Internet
Author: User
Tags nginx server

Suppose there is a site A, it has a simple input user name of the page, the interface has two input boxes, the first input box is contained in a form form to implement the form submission, the second input box is separate, not included in the form, the following two input boxes to learn the jquery Ajax.

1, front-end HTML and JavaScript code

Page HTML

<main style="text-align:center; margin:200px auto;"> class=""action="demo01.php"Method="Post"style="margin-bottom:20px;"> <input id="User-name"Type="text"Name="username"Placeholder="please fill in your user name"> <input type="Submit"Name="Submit1"Value="form submission 1" class="input"> </form> <input id="user-name2"Type="text"Name="username2"Placeholder="please fill in your user name"> <input type="Button"Name="Submit2"Value="Ajax Submission 2"> <divclass="Box"> </div> </main> <script src=".. /.. /js/jquery-3.1.0.min.js"></script> <script src="Demo01.js"></script>
View Code

The Demo01.js code introduced in the page, note that a simple GET request is implemented here.

$ (function ($) {$ ('Input[name=submit2]'). On ('Click', Function (e) {let username="'; if("'!== (username = $ ('#user-name2'). Val ())) {$.ajax ({url: ' demo0.php?name=${username} ', DataType:'JSON', Method:'GET', Success:function (data) {if(Data.result = = 1) {                        $('. Box'). HTML (' <div> your name ${username} was saved successfully. </div>`); }}, Error:function (XHR) {//the cause of the error is more, and later on alert ('Error:'+json.stringify (XHR)); }}). Done (function (data) {//work to be done after the request is successful Console.log ('Success'); }). Fail (function () {//work to do after a request fails Console.log ('Error'); }). Always (function () {//work to be done regardless of success or failure Console.log (' Complete');        }); }    });});
View Code

The Ajax () method of jquery is written in two ways: $.ajax (URL [, Settings]); and $.ajax ([Settings]); Both ways can be used to feel that the first method is suitable for use in fewer parameters, for example, if you just make a simple request to a URL, not to return the data, format and error requirements, only need to pass a URL parameter can be, then you can use the first one of the notation. The second method is used in the demo01.js above, and the following parameters and related functions are explained below.

(1) The Parameters of Ajax () in the above code
You can see that the parameter types here are JavaScript objects, which are all o = {Key:value}; This type of data. The jquery documentation specifies that the parameters here are only Plainobject (objects of object type), cannot be null, custom arrays, or objects that belong to some kind of execution environment (such as a browser), such as Docement. It's not quite clear here, but you can do a little experiment. Open node Repl at the command line and test it:

> node> typeof (null); ' Object '> typeof ([]); ' Object '> typeof (document); ' undefined '> typeof ({}); ' Object '
View Code

You can see that null, [] (array type), {} (object type) are objects. Because in JS everything is the object. In an interactive environment, document is a variable that is undefined, so its type is undefined. If you test under typeof (document) under a browser environment, it is also an object type. The following is an explanation of the parameters used in the code:

URL, the URL address to request, and its value should be a string containing the URL.

DataType, String. The type of data expected to be returned from the server after the request is made. The types you can specify are XML, HTML, script, JSON, JSONP, text. If not specified, jquery is judged based on MIME and returns a type in the following XML, JSON, script, and HTML.

Method, String. The HTTP request method, which defaults to get, is specified in the code above as post.

Success, type:function (anything data, String Textstatus, jqxhr jqxhr), anonymous function. The function to be called after the HTTP request succeeds, you can pass three parameters to it: The data returned from the server (if datatype is specified above, the data type returned by the server needs to be the same as the type specified above datatype), a string that can describe the state textstatus, There is also a Jqxhr object. You can see that only the data returned from the server is passed on above.

Error, Type:function (jqxhr jqxhr, String textstatus, String errorthrown), anonymous function. A function to be called after an HTTP request fails, as well as passing three parameters.

In addition to these parameters, there are many other parameters, such as async, Datafilter, MimeType, and so on, but now this simple script does not have so many parameters.

(2) "Lazy load function"

In the code above, $.ajax (). Done (). Fail (). Always () Jqxhr.done (), Jqxhr.fail (), jqxhr.always () can add deferred objects to be parsed, rejected, The work to be handled in these three cases, such as adding a function or something, is resolved or rejected. Why you can do this depends on what $.ajax () returns, which returns the Jqxhr object (when the jquery version is greater than 1.5). This object implements the Promise interface (promise mechanism, which is used to pass an asynchronous operation message that represents a future event that will know the result). This allows multiple callback functions to be added to a single request, and even a callback function can be added after the request is completed.

The title "Lazy loading" is not accurate enough to describe, but the effect is that it has a lazy loading effect. A more detailed explanation of the problem can be found in the jquery document's explanation of JQXHR or a front-end predecessor's explanation of jquery's deferred object.

2, the back end of the PHP code running on the Nginx server

The logic behind the backend is simple: we save the data from the front end to a file named Data-demo01, and the Save succeeds returns a 1 as a flag to the front end.

(1) Front-end Ajax initiating GET request

If the front-end Ajax initiates a GET request, then the backend is also better handled:

 if  (isset ($_get[ '  name  " ]) &&!empty ($_get[  " name   " )) {$username  = Trim ($_get[ " name  "  ]);  if  (file_put_contents ( " data-demo01   " , $ username) {echo   " {" result ": 1}   "        ; }         }
View Code

(2) Front-end Ajax initiating POST request

JS code needs to modify the next Ajax () URL, method parameter, and add a data parameter, modified as follows:

the same code omits $.ajax ({    URL: ' demo01.php ',    'json',    '  POST',    data: {"username": Username},//the same code omitted
View Code

Because the data is passed by post, the parameters used to pass the data in the URL are removed, and the following data type is consistent with datatype, in JSON format, and then passed as the value username.

Then the backend code can be determined as well:

 if  (isset ($_post[ " username  " ]) &&!empty ($_post["  username   "  = Trim ($_post[ " username  "  ]);  if  (file_put_contents ( " data-demo01   " , $ username) {echo   " {" result ": 1}   "        ; }    }
View Code

If it doesn't go wrong, the name should be saved.

Ajax makes get and post requests to the server

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.