Home > Web Front-end > JS Tutorial > How jQuery issues get and post requests to the server

How jQuery issues get and post requests to the server

php中世界最好的语言
Release: 2018-04-25 14:18:57
Original
1827 people have browsed it

This time I will show you how jQuery issues get and post requests to the server. What are the precautions for jQuery to issue get and post requests to the server? The following is a practical case, let's take a look.

Suppose there is a website A, which has a simple page for entering a user name. There are two input boxes on the interface. The first input box is included in a form and is used to implement form submission. The input boxes are separate and not included in the form. Let’s use these two input boxes to learn jQuery’s ajax.

1, front-end html and javascript code

page html

<main style="text-align: center; margin: 200px auto;">
   <h2>输入用户名</h2>
   <form class="" action="demo01.php" method="post" style="margin-bottom: 20px;">
   <input id="user-name" type="text" name="username" placeholder="请填写您的用户名">
    <input type="submit" name="submit1" value="form提交1" class="input">
   </form>
   <input id="user-name2" type="text" name="username2" placeholder="请填写您的用户名">
   <input type="button" name="submit2" value="ajax提交2">
   <p class="box">
   </p>
  </main>
  <script src="../../js/jquery-3.1.0.min.js"></script>
  <script src="demo.js"></script>
Copy after login

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

 $(function($) {
  $('input[name=submit2]').on('click', function(e) {
   let username = '';
   if ('' !== (username = $('#user-name2').val())) {
    $.ajax({
     url: `demo.php?name=${username}`,
     dataType: 'json',
     method: 'GET',
     success: function(data) {
      if (data.result == 1) {
       $('.box').html(`<p>你的姓名${username}已成功保存。</p>`);
      }
     },
     error: function(xhr) {
      // 导致出错的原因较多,以后再研究
      alert('error:' + JSON.stringify(xhr));
     }
    })
    .done(function(data) {
     // 请求成功后要做的工作
     console.log('success');
    })
    .fail(function() {
     // 请求失败后要做的工作
     console.log('error');
    })
    .always(function() {
     // 不管成功或失败都要做的工作
     console.log('complete');
    });
   }
  });
 });
Copy after login

jQuery's ajax() method has two ways of writing, namely: $.ajax(url [, settings]); and $.ajax([settings]); Both ways of writing are OK. I feel like One method is suitable for situations with fewer parameters. For example, if you just make a simple request for a URL, there are no requirements for the returned data, format, and errors. You only need to pass a URL parameter, then you can use the second method. A way of writing. The above demo01.js uses the second writing method. The 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 all javascript objects, that is, they are all o = {key: value}; This type of data. The jQuery documentation stipulates that the parameters here can only be PlainObject (object type objects), not null, custom arrays, or docements that belong to a certain execution environment (such as a browser) and belong to a certain type. Object. It’s not easy to explain clearly here, you can do a small experiment. Open node repl in the command line and conduct the following test:

> node
 > typeof(null);
 'object'
 > typeof([]);
 'object'
 > typeof(document);
 'undefined'
 > typeof({});
 'object'
Copy after login

You can see that null, [] (array type), {} (object type) are all objects. Because everything in js is an object. In an interactive environment, document is an undefined variable, so its type is undefined. If typeof(document) is tested in a browser environment, its type is also object. The parameters used in the code are explained one by one below:

url, the URL address to be requested, its value should be a string containing the URL.

dataType, string. The type of data to expect back from the server after making a request. The types that can be specified are xml, html, script, json, jsonp, and text. If not specified, jquery will make a judgment based on MIME and return one of the following types: xml, json, script, and html.

method, string. HTTP request method, the default is GET, and the above code specifies POST.

success, Type: Function(Anything data, String textStatus, jqXHR jqXHR), anonymous function. The function to be called after a successful HTTP request 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 consistent with the type specified by dataType above), a state that can be described The string textStatus, and a jqXHR object. You can see that only the data returned from the server is passed above.

error, Type: Function(jqXHR jqXHR, String textStatus, String errorThrown), anonymous function. The function to be called after the HTTP request fails can also pass three parameters.

In addition to these parameters, there are many other parameters such as: async, dataFilter, mimeType and other parameters, but the current simple script does not use so many parameters.

(2) "Lazy loading function"

In the above code $.ajax().done().fail().always() jqXHR.done( ), jqXHR.fail(), and jqXHR.always() can respectively add work to be processed when the deferred object is parsed, rejected, parsed, or rejected, such as adding a function or something. Why this can be done depends on what $.ajax() returns. It returns a jqXHR object (when the jquery version is greater than 1.5). This object implements the Promise interface (Promise mechanism, used to deliver asynchronous operation messages, representing an event whose result will not be known until the future). This allows multiple callback functions to be added in a single request, and even callback functions can be added after the request is completed.

标题“延迟加载”描述的不够准确,但从效果上看是有延迟加载的效果。关于这个问题更详细的解释可以参考jQuery文档中对jqXHR的解释  或一位前端前辈的解释jQuery的deferred对象详解 。

 2,后端运行在nginx服务器上的php代码

后端的逻辑很简单:我们把前端获取的数据保存到名为data-demo01的文件中,保存成功则向前端返回一个1作为标志。

(1)前端ajax发起GET请求

如果前端的ajax发起的是一个GET请求,那么后端也比较好处理:

  if (isset($_GET['name']) && !empty($_GET['name'])) {
   $username = trim($_GET['name']);
   if (file_put_contents('data-demo01', $username)) {
    echo '{"result": 1}';
   } 
}
Copy after login

(2)前端ajax发起POST请求

js代码中需要修改下ajax()的url、method参数,并增加一个data参数,修改后如下:

 // 相同的代码省略
 $.ajax({
  url: `demo01.php`,
  dataType: 'json',
  method: 'POST',
  data: {"username": username},
 // 相同的代码省略
Copy after login

因为用POST传递数据,所以去掉url中用来传递数据的参数,下面的data类型要与dataType一致,为json格式,然后将username作为值传递。

那么后端的代码也就可以确定了:

 if (isset($_POST['username']) && !empty($_POST['username'])) {
   $username = trim($_POST['username']);
   if (file_put_contents('data-demo01', $username)) {
    echo '{"result": 1}';
   }
  }
Copy after login

如果不出错的话,效果应该是下面这样然后查看下data-demo01,名字果然被保存了。

那么问题来了,如果出错了呢?比如data-demo01文件不可写,或者后台服务器返回的数据格式有错误,或者网络出错。那又该怎么处理呢?我现在也不太清楚,后续再研究吧。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

html直接显示JSON方法详解

PHP操作JSON方法大全

The above is the detailed content of How jQuery issues get and post requests to the server. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template