AngularJS uses $http service POST to submit data

        The version of AngularJS I use is version 1.6.0. The following code may not be universal and is for reference only.

        Calling ajax in AngularJS will use the $http service, a simple example of using the $http service to initiate a POST request.

$http({  
		method:'post',  
		url:'${ctx}/province/handler/get',  
		data:{id:'${provinceId}'}  
}).then(
	function(result){  
		//do something
	}
);  

    Initially, the then method was not used for the callback, but the success method was used. The reason for the success method is to refer to the writing method in many blogs. The success and error methods have been deprecated in version 1.6.0.

     Call this method directly in the Controller defined in the page, you can use ajax, so I put this idea into practice, the result is different from what I expected, the ajax request is successful, but the angular rendering fails, and this time The console doesn't have any exceptions. After logging out the code above, angular renders fine. At first, I guessed that it is conditional for AngularJS to call the $http service. After all, $http is asynchronous, and it must be called after all renderings are completed. So I modified my code and waited until the angular rendering was completed, and then initiated the ajax request.

//AngularJS rendering is complete
			$scope.$watch('$viewContentLoaded', function() {
				 $scope.get();
			});
			
			//Trigger event when rendering is complete
			//define a method to call
			 $scope.get=function(){
					$http({  
						   method:'post',  
						   url:'${ctx}/province/handler/get',  
						   data:{id:'${provinceId}'}  
					}).then(
						function(result){  
							
				   		}
					);  	
			};

    After modifying the code, the FireFox console finally reported an error. After checking, it was caused by the plug-in firebug in firefox. It is recommended to replace other browsers or remove the firebug plug-in. At this time, there is no exception under the google browser, and the angular rendering is successful. At this time, the firebug plugin is removed, and the firefox browser is displayed normally.

    Because the Firebug plug-in is installed in the Firefox browser, the above rendering failure problem will occur, and the problem will be solved after removing the plug-in. At this time, the above two ways of writing can be called normally.

    There is also a third way of writing, which is very similar to the first way, but the third way to write it is to declare the function first, and then call it.

//define a method to call
			 $scope.get=function(){
					$http({  
						   method:'post',  
						   url:'${ctx}/province/handler/get',  
						   data:{id:'${provinceId}'}  
					}).then(
						function(result){  
							
				   		}
					);  	
			};
			//declare before calling method
			$scope.get();

 

     

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326986649&siteId=291194637