Vue.js Ajax (vue-resource)
To implement asynchronous loading in Vue, you need to use the vue-resource library.
For Vue.js 2.0, it is recommended to use axios to handle ajax requests.
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
GET Request
Below is a simple example of a GET request, where the request address is a simple txt file:
Example
window.onload = function(){
var vm = new Vue({
el:'#box',
data:{
msg:'Hello World!',
},
methods:{
get:function(){
// Send GET request
this.$http.get('/try/ajax/ajax_info.txt').then(function(res){
document.write(res.body);
},function(){
console.log('Request failed processing');
});
}
}
});
}
If you need to pass data, you can use the format this.$http.get('get.php', {params: jsonData})
, where jsonData is the data sent to the backend.
this.$http.get('get.php', {params: {a: 1, b: 2}}).then(function(res){
document.write(res.body);
}, function(res){
console.log(res.status);
});
POST Request
To send data to the backend with POST, you need the third parameter {emulateJSON: true}
.
The purpose of emulateJSON: If the web server cannot handle requests encoded as application/json, you can enable the emulateJSON option.
Example
window.onload = function(){
var vm = new Vue({
el:'#box',
data:{
msg:'Hello World!',
},
methods:{
post:function(){
// Send POST request
this.$http.post('/try/ajax/demo_test_post.php', {name: "tutorialpro.org", url: "http://www.tutorialpro.org"}, {emulateJSON: true}).then(function(res){
document.write(res.body);
}, function(res){
console.log(res.status);
});
}
}
});
}
The demo_test_post.php code is as follows:
<?php
$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$city = isset($_POST['url']) ? htmlspecialchars($_POST['url']) : '';
echo 'Website Name: ' . $name;
echo "\n";
echo 'URL Address: ' . $city;
?>
Syntax & API
You can use the global Vue.http object or this.$http within a Vue instance to initiate HTTP requests.
// Using http based on the global Vue object
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback); Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
// Using $http within a Vue instance this.$http.get('/someUrl', [options]).then(successCallback, errorCallback); this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
get(url, [options]) head(url, [options]) delete(url, [options]) jsonp(url, [options]) post(url, [body], [options]) put(url, [body], [options]) patch(url, [body], [options]) ```
Except for jsonp, the other six API names are standard HTTP methods.
Options parameter description:
Parameter | Type | Description |
---|---|---|
url | string | The target URL for the request |
body | Object, FormData, string | Data sent as the request body |
headers | Object | Headers object sent as the request headers |
params | Object | Parameter object as URL parameters |
method | string | HTTP method (e.g., GET, POST, ...) |
timeout | number | Request timeout (in milliseconds) (0 means never timeout) |
before | function(request) | Callback function to modify the request before it is sent |
progress | function(event) | Callback function for handling upload progress ProgressEvent |
credentials | boolean | Whether to send credentials for cross-site requests |
emulateHTTP | boolean | Whether to set the X-HTTP-Method-Override header and send PUT, PATCH, and DELETE requests as traditional POST |
emulateJSON | boolean | Set the request body type to application/x-www-form-urlencoded |
Handle the response object obtained from a request with the following properties and methods:
Property | Type | Description |
---|---|---|
url | string | The source URL of the response |
body | Object, Blob, string | Response body data |
headers | Header | Headers object |
ok | boolean | True if the HTTP response code is between 200 and 299 |
status | number | HTTP response code |
statusText | string | HTTP response status |
Method | Type | Description |
text() | Promise | Returns the response body as a string |
json() | Promise | Returns the response body as a formatted json object |
blob() | Promise | Returns the response body as a binary Blob object |