$http service content in AngularJS
Use $http shortcut method to interact with the server
In AngularJS, the interaction between the page and the server mainly involves calling modules.
Depending on the request type, the $http module provides different calling methods. Its general format is as follows.
Parameter explanation:
url: Indicates a relative or absolute server request path;
Request type: includes There are six common request methods: POST, GET, JSONP, DELETE, PUT, and HEAD. Among them, POST and PUT type requests can send data through the optional parameter data, and can also set the data passed during the request through the optional parameter config.
When the $http request is successful, you can obtain the data and related information returned by the server in the success method of the callback.
data: Indicates the parameter return body, usually the result set returned by the request.
status: Indicates the status value returned after the request.
headers: Indicates the header file returned after the request, used to display the header information of the returned request.
config: is an object through which the complete configuration information when sending an HTTP request can be obtained.
Use $http configuration object to interact with the server
Above we introduced the process of using the /$http shortcut to interact with the server. Although this method is simple, it lacks flexibility in configuration and requires a lot of code. In response to this situation, we can use the \$http service template as a function, treat all configuration items that construct the XHR object as an object, and define the object as the formal parameter of the function. When calling, only need to modify the object Each attribute value is sufficient. The specific calling format is as follows.
$http({ method: //表示请求方式,是字符串,常有POST、GET、JSONP、DELETE、PUT、HEAD六种方式 url: //表示向服务器请求的地址 data: //是一个对象,在使用POST/PUT时,该对象将作为消息体的一部分发给服务端 params: //是字符串或对象,发送HTTP请求时,如果是对象,将自动按json格式进行序列化,并追加到url后面,作为发送数据的一部分,传递给服务器。 transformRequest://对请求体信息和请求体进行序列化转换,并生成一个数组发送给服务端。 transformResponse://对相应体头信息和相应体进行反序列化转换,其实质就是解析服务器发送来的被序列化后的数据。 cache://布尔值(true/false),表示是否对http请求返回的数据进行缓存,如果设置为true,则表示需要缓存。 timeout://表示延迟http请求的时间,单位是毫秒。})
For example:
Requirement description:
Add a text box button to the page. , when the user enters a number in the text box and clicks the button, the $http function is called to send an HTTP request to the server, verify the parity of the number, and display the verification result in the page element.
<!DOCTYPE html><html ng-app="a7_3"><head> <meta charset="UTF-8"> <title>使用$http配置对象方式与服务端交互</title> <script src="../script/angular.min.js"></script> <link href="Css/css7.css" rel="stylesheet" ></head><body> <p class="frame" ng-controller="c7_3"> <p class="show"> <input type="text" ng-model="num"> <button ng-click="onclick()">验证奇偶</button> <p class="tip">您输入的是:{{result}}</p> </p> </p> <script type="text/javascript"> angular.module('a7_3',[]) .controller('c7_3',function($scope,$http){ $scope.num = 0; $scope.result = "偶数"; $scope.onclick = function(){ $http({ method: 'GET', url: 'data/chk.php', params:{ n: $scope.num } }).success(function(data,status,headers,config){ $scope.result = data; }) } }); </script> </body> </html>
Analysis:
In the js code of this example, when the user clicks the button, the onclick method bound to the button is triggered. In this method, the $http service is called , and pass parameters to the function in the form of configuration objects, such as method, url and other attribute values.
Because the GET request is used, the value in the text box is passed to the server in the form of key/value through the params attribute. .
In this example, the final content of the requested URL is
htpp://localhost/Ch7/data/chk.php?n=87, where n is the key name and 87 is the key value, which is the text box The number entered in .
When the /$http function sends an HTTP request, you can use the successes method to obtain the data content and other header information returned by the server. For example, data is the returned data, which is the number entered by the user in the text box.
In Angular, after executing the /$http function, its return content is actually a promise object. Therefore, you can directly call the then method through chain writing to obtain success and exception data.
The following two pieces of code have the same function.
$http({//配置对象}) .succes(fn1) .error(fn2)
is equivalent to
$http({//配置对象 }) .then(fn1,fn2)
fn1 and fn2 respectively represent the return functions of request success and error.
Although the functions of both are the same. However, using the then method can receive the complete response object from the server, while the success and error methods only receive the parsed and processed response object, which means that the return object obtained by the then method is more original and complete.
The above is the detailed content of $http service content in AngularJS. 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

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to implement HTTP streaming in C++? Create an SSL stream socket using Boost.Asio and the asiohttps client library. Connect to the server and send an HTTP request. Receive HTTP response headers and print them. Receives the HTTP response body and prints it.

The HTTP request times out, and the server often returns the 504GatewayTimeout status code. This status code indicates that when the server executes a request, it still fails to obtain the resources required for the request or complete the processing of the request after a period of time. It is a status code of the 5xx series, which indicates that the server has encountered a temporary problem or overload, resulting in the inability to correctly handle the client's request. In the HTTP protocol, various status codes have specific meanings and uses, and the 504 status code is used to indicate request timeout issues. in customer

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Solution: 1. Retry: You can wait for a period of time and try again, or refresh the page; 2. Check the server load: Check the server's CPU, memory and disk usage. If the capacity limit is exceeded, you can try to optimize the server configuration or increase the capacity. Server resources; 3. Check server maintenance and upgrades: You can only wait until the server returns to normal; 4. Check network connection: Make sure the network connection is stable, check whether the network device, firewall or proxy settings are correct; 5. Ensure cache or CDN configuration Correct; 6. Contact the server administrator, etc.
