How jQuery issues get and post requests to the server
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>
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'); }); } }); });
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'
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}'; } }
(2)前端ajax发起POST请求
js代码中需要修改下ajax()的url、method参数,并增加一个data参数,修改后如下:
// 相同的代码省略 $.ajax({ url: `demo01.php`, dataType: 'json', method: 'POST', data: {"username": username}, // 相同的代码省略
因为用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}'; } }
如果不出错的话,效果应该是下面这样然后查看下data-demo01,名字果然被保存了。
那么问题来了,如果出错了呢?比如data-demo01文件不可写,或者后台服务器返回的数据格式有错误,或者网络出错。那又该怎么处理呢?我现在也不太清楚,后续再研究吧。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The role of a DHCP relay is to forward received DHCP packets to another DHCP server on the network, even if the two servers are on different subnets. By using a DHCP relay, you can deploy a centralized DHCP server in the network center and use it to dynamically assign IP addresses to all network subnets/VLANs. Dnsmasq is a commonly used DNS and DHCP protocol server that can be configured as a DHCP relay server to help manage dynamic host configurations in the network. In this article, we will show you how to configure dnsmasq as a DHCP relay server. Content Topics: Network Topology Configuring Static IP Addresses on a DHCP Relay D on a Centralized DHCP Server

In network data transmission, IP proxy servers play an important role, helping users hide their real IP addresses, protect privacy, and improve access speeds. In this article, we will introduce the best practice guide on how to build an IP proxy server with PHP and provide specific code examples. What is an IP proxy server? An IP proxy server is an intermediate server located between the user and the target server. It acts as a transfer station between the user and the target server, forwarding the user's requests and responses. By using an IP proxy server

What should I do if I can’t enter the game when the epic server is offline? This problem must have been encountered by many friends. When this prompt appears, the genuine game cannot be started. This problem is usually caused by interference from the network and security software. So how should it be solved? The editor of this issue will explain I would like to share the solution with you, I hope today’s software tutorial can help you solve the problem. What to do if the epic server cannot enter the game when it is offline: 1. It may be interfered by security software. Close the game platform and security software and then restart. 2. The second is that the network fluctuates too much. Try restarting the router to see if it works. If the conditions are OK, you can try to use the 5g mobile network to operate. 3. Then there may be more

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

How to install PHPFFmpeg extension on server? Installing the PHPFFmpeg extension on the server can help us process audio and video files in PHP projects and implement functions such as encoding, decoding, editing, and processing of audio and video files. This article will introduce how to install the PHPFFmpeg extension on the server, as well as specific code examples. First, we need to ensure that PHP and FFmpeg are installed on the server. If FFmpeg is not installed, you can follow the steps below to install FFmpe

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

PHP is a programming language widely used in website development, and page jumps and carrying POST data are common requirements in website development. This article will introduce how to implement PHP page jump and carry POST data, including specific code examples. In PHP, page jumps are generally implemented through the header function. If you need to carry POST data during the jump process, you can do it through the following steps: First, create a page containing a form, where the user fills in the information and clicks the submit button. Acti in the form

Golang is an open source programming language developed by Google. It is efficient, fast and powerful and is widely used in cloud computing, network programming, big data processing and other fields. As a strongly typed, static language, Golang has many advantages when building server-side applications. This article will analyze the advantages and utility of Golang server in detail, and illustrate its power through specific code examples. 1. The high-performance Golang compiler can compile the code into local code
