Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Class7/requests.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
51 lines (39 sloc)
1.2 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createPost(event) { | |
event.preventDefault(); | |
var inputs = document.forms[0].elements; | |
var formData = {}; | |
formData.title = inputs.title.value; | |
formData.post = inputs.post.value; | |
createHTML(formData); | |
//POST request | |
var request = new XMLHttpRequest(); | |
request.open('POST','https://jsonplaceholder.typicode.com/posts'); | |
request.send(JSON.stringify(formData)); | |
request.onload = function() { | |
console.log(request.response); | |
} | |
} | |
function createHTML(data) { | |
console.log(data); | |
var container = document.getElementById('posts'); | |
var heading = document.createElement('h2'); | |
heading.innerText = data.title; | |
container.appendChild(heading); | |
if(data.post) { | |
var postBody = document.createElement('p'); | |
postBody.innerText = data.post; | |
container.appendChild(postBody); | |
} | |
} | |
function requestTodo() { | |
var request = new XMLHttpRequest(); | |
//specify verb and URL | |
request.open('GET', 'https://jsonplaceholder.typicode.com/todos/1'); | |
//send request | |
request.send(); | |
//response | |
request.onload = function() { | |
var response = JSON.parse(request.response); | |
createHTML(response); | |
} | |
} |