04 练习:向服务器请求 JSON 数据并解析
<script type="text/javascript">
window.onload = function () {
//获取XMLHttpRequest
xmlhttp = new XMLHttpRequest()
xmlhttp.open("GET","book.json",false)
xmlhttp.send()
//获得 json 字符串
var jsonStr = xmlhttp.response
alert(jsonStr)
//将 json 字符串转换为 json 对象
var json = JSON.parse(jsonStr)
var writeStr = "ID = "+json.id+
"<br/>name = "+json.name+
"<br/>price = "+json.price
document.write(writeStr)
}
</script>
book.json
{"id": "001","name": "java 进阶","price": 50}
XMLHttpRequest 对象的 open() 和 send() 方法详解:
方法 | 描述 |
---|---|
open(method,url,async) | 规定请求的类型、URL 以及是否异步处理请求。 method:请求的类型(GET 或 POST) url:文件在服务器上的位置 async:true(异步)或 false(同步) |
send(string) | 将请求发送到服务器。 string:仅用于 POST 请求 |