ChingFeng
Sep 9, 2018 · 3 min read

VueJs Ajax篇-XMLHttpRequest(三)

表單資料

透過http://jsonplaceholder.typicode.com/posts來取得回傳資料

◉應用

=【Html】=
— — — — — — — — — — — —
<div id="app">
<h3>Write a new post</h3>
<form>
<div>
<label>Title of your post:</label>
<input type="text" v-model="title">
</div>
<div>
<label>Write your thoughts for the day</label>
<textarea v-model="body"></textarea>
</div>
<div>
<button @click.prevent="submit">Submit</button>
</div>
</form>
<h3>Response form the server</h3>
<pre>{{response}}</pre>
</div>
— — — — — — — — — — — —
=【VueJs】=
— — — — — — — — — — — —
new Vue({
el: '#app',
data: {
userId: 1,
title: '',
body: '',
response: '...'
},
methods: {
submit () {
const xhr = new XMLHttpRequest()
xhr.open('post', 'http://jsonplaceholder.typicode.com/posts')
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
xhr.onreadystatechange = () => {
const DONE = 4
const CREATED = 201
if (xhr.readyState === DONE) {
if (xhr.status === CREATED) {
this.response = xhr.response
} else {
this.response = 'Error: ' + xhr.status
}
}
}
xhr.send(JSON.stringify({
title: this.title,
body: this.body,
userId: this.userId
}))
}
}
})

Object實戰

學習歷程紀錄

ChingFeng

Written by

叢林般的世界,一步步邁向未知的未來,迴盪迷途的工程師…

Object實戰

學習歷程紀錄

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade