JSON和JS对比
https://www.json.org/json-en.html
- JSON没有采用JS的function和undefined
- JSON的字符串首尾必须是“”双引号
- 数据对应
JS | JSON |
undefined | 没有 |
function fn(){} | 没有 |
var a={};a.self = a | 没有 |
null | null |
['q','w'] | ["q","w"] |
'qwer' | "qwer" |
{__proto__} | 没有原型链 |
注:后端不可能给前端返回对象,会返回字符串
同源策略
ajax无法给其他域名发送请求,而SJD,script标签,img标签,link标签方法是可以的。
只有协议+端口+域名一模一样才可以发送AJAX请求
为什么AJAX会有同源策略?
https://www.zhihu.com/question/31592553
但是如果想要发跨域访问怎么办?
使用JSONP
使用AJAX、CORS告诉浏览器这两个域名可以访问
response.setHeader('Access-Control-Allow-Origin','http://www.xxxx.com:8000')
CORS:Cross-Origin Resourse Share 跨站资源共享
AJAX请求基本代码
let request = new XMLHttpRequest()
request.open()//配置请求
request.send()//发送请求
request.onreadystatechange = ()=>{
if(request.readyState === 4){
if(request.status >= 200 && request.status < 300){
let string = request.responseText
let object = window.JSON.parse(string)
}
}
}