批改状态:合格
老师批语:
test1.php
<?php// 允许跨域header('Access-Control-Allow-Origin: *');// 输出 JSON 字符串echo json_encode(['uname'=> '马老师', 'email'=> '5678@qq.com' ]);
<body><button onclick="getData()">fetch 跨域请求</button><script>function getData() {// 1. fetch(url): 向一个url发请异步请求fetch(`http://world.io/test1.php`)// 2. then(response=>response.json()), 将返回结果转换为 JSON 字符串.then(res => res.json())// 3. then(json=>console.log(json)),接下来就可以处理第2步的 JSON 字符串了.then(json => {document.body.insertAdjacentHTML('beforeend', `<p>${json.uname}</p>`)})}</script></body>
点击按钮,页面输出请求的数据:
<body><button onclick="getData(this)">async 跨域请求</button><script>// 异步函数,前面加 asyncasync function getData(ele) {const url = 'http://world.io/test1.php'try {// 1. 发起异步请求,等待返回结果的响应对象const response = await fetch(url)// 2. 如果响应成功,将响应结果转为jsonconst result = await response.json()// 3. 对响应结果进行处理,例如渲染到到页面,或打印到控制台查看ele.insertAdjacentHTML('afterend', `<p>${result.email}</p>`)} catch {console.error('请求失败')}}</script></body>
点击按钮,页面输出请求的数据:
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号