Last active
January 26, 2017 16:06
-
-
Save yuqianma/31f73e64424d0699740de672d26e8eba to your computer and use it in GitHub Desktop.
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 fetchData(url, cb) { | |
var xhr = new XMLHttpRequest() // 新建一个请求对象,如果需要文档,查XMLHttpRequest | |
xhr.open('GET', url) // get类型, url;注意此时请求还没有发送 | |
xhr.onload = function() {cb(xhr.responseText)} // 写好callback回调函数,因为js是异步的,只用通过回调函数接收参数来获取。 | |
xhr.send() // 发送请求,这里才是真的开始请求,请求成功的话回调就成功了;post在这里发送数据 | |
} | |
(function () { | |
var callback = function (str) { | |
var data = JSON.parse(str) // JSON.parse, JSON.stringify 互相转换 | |
var name = data['name'], sex = data.sex; // object['key']或者object.key都可以,但前一种可以为一个变量 | |
// ... | |
// 所有获取数据后要做的操作 | |
// 因为js是异步的 | |
var dom = document.querySelectorAll('#container .name')[0] // or document.querySelector(), get first one | |
dom.textContent = name // text | |
dom.innerHTML = '<div></div>' // html | |
}; | |
fetchData('http://www.test.com?query=id', callback) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment