-
-
Notifications
You must be signed in to change notification settings - Fork 3
Response Handling
Fatih Koca edited this page Nov 27, 2019
·
3 revisions
The response returns the Object on the frontend.
Success and error together in then()
method:
Vue.ajax({url: "http://example.com"})
.then(function(response) {
console.log(response.data);
}, function(response) {
console.log(response);
})
Success and error together in separate methods:
Vue.ajax({url: "http://example.com"})
.then(function(response) {
console.log(response.data);
})
.catch(function(response) {
console.log(response);
})
The object in general is the following structure:
Vue.ajax.post("http://example.com", {pageNumber: 5})
.then(function(response) {
console.log(response.data)
});
Response Property | Type |
---|---|
data | Object Or String |
status | String |
statusText | String |
headers | String |
config | Object |
xhrStatus | String |
request | Object |
If the content type on the server is "application/json
", the response.data
is automatically converted to a JSON object
. If the content type is anything else, the result is returned as plain text
.
PHP:
header("Content-type: application/json; charset=utf-8");
echo json_encode($array);
PHP (Laravel):
Route::get("http://example.com", function () {
return json_encode($array);
});
Vue.js
Vue.ajax.get("http://example.com", {})
.then(function(response) {
console.log(response.data)
});
There are two ways to use:
Vue.ajax.get("http://example.com/not-existing-path", [data])
.then(function(response) {
console.log(response.data)
}, function(response) {
console.log("Error: ", response.statusText);
}); // "Error: Not Found"
Vue.ajax.get("http://example.com/not-existing-path", [data])
.then(function(response) {
console.log(response.data)
}).catch(function(response) {
console.log("Error: ", response.statusText);
}); // "Error: Not Found"