YouTip LogoYouTip

Vuejs Ajax

Vue.js Ajax (vue-resource)

Vue.js requires the vue-resource library to implement asynchronous loading.

For Vue.js 2.0, it is recommended to use axios to handle Ajax requests.

GET Request

Here is a simple GET request example. The request URL points to a simple text file:

Example

window.onload = function(){
    var vm = new Vue({
        el:'#box',
        data:{
            msg:'Hello World!',
        },
        methods:{
            get:function(){
                this.$http.get('/try/ajax/ajax_info.txt').then(function(res){
                    document.write(res.body);
                },function(){
                    console.log('Request failed.');
                });
            }
        }
    });
}

Try it yourself Β»

If you need to pass data, you can use the format this.$http.get('get.php', {params: jsonData}), where the second parameter 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 via POST, a third parameter {emulateJSON: true} is required.

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(){
                this.$http.post('/try/ajax/demo_test_post.php', {name:"", url:""}, {emulateJSON:true}).then(function(res){
                    document.write(res.body);
                }, function(res){
                    console.log(res.status);
                });
            }
        }
    });
}

Try it yourself Β»

The code for demo_test_post.php 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: ' . $city;
?>

Syntax & API

You can use the global object Vue.http or this.$http within a Vue instance to make HTTP requests.

// Using http based on the global Vue object
Vue.http.get('/someUrl', ).then(successCallback, errorCallback);
Vue.http.post('/someUrl', , ).then(successCallback, errorCallback);

// Using $http within a Vue instance
this.$http.get('/someUrl', ).then(successCallback, errorCallback);
this.$http.post('/someUrl', , ).then(successCallback, errorCallback);

vue-resource provides 7 request APIs (RESTful style):

  • get(url, )
  • head(url, )
  • delete(url, )
  • jsonp(url, )
  • post(url, , )
  • put(url, , )
  • patch(url, , )

Except for jsonp, the other 6 API names are standard HTTP methods.

options parameter description:

Parameter Type Description
url string Target URL for the request
body Object, FormData, string Data sent as the request body
headers Object Header object sent as request headers
params Object Parameter object sent as URL parameters
method string HTTP method (e.g., GET, POST, ...)
timeout number Request timeout in milliseconds (0 means no 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 include credentials for cross-site requests
emulateHTTP boolean Whether to send PUT, PATCH, and DELETE requests via a traditional POST method by setting the X-HTTP-Method-Override header.
emulateJSON boolean Set the request body type to application/x-www-form-urlencoded

Handle the response object obtained from a request using the following properties and methods:

Property Type Description
url string Source URL of the response
body Object, Blob, string Response body data
headers Header Response header object
ok boolean True when the HTTP status code is between 200 and 299
status number HTTP status code
statusText string HTTP status text
Method Type Description
text() Promise Returns the response body as a string
json() Promise Returns the response body as a parsed JSON object
blob() Promise Returns the response body as a binary Blob object
← Maven TutorialMet Cssstyle Item β†’