JavaScript处理get请求无非就是三种方式
第一种:使用第三方插件,例如 url;
第二种:借助于正则表达式 ;
第三种:借助于 String 方法;
第一种方式:使用url插件
- 安装
npm install url -S
- 在文件中引入
import url from 'url'
- 使用
// 适用于组件之间的路由跳转,根据自己的场景选择要在哪个组件的生命周期或者自定义的方法中执行,本例是在 componentDidMount中使用
componentDidMount(){
console.log(url.parse(this.props.location.search, true).query)
}
第二种方式:借助于正则表达式
本例用到了正则表达式的字符类、重复、分组及RegExp的exec()方法。可参考《JavaScript权威指南》
var args = {}
var match = null
var search = decodeURIComponent(this.props.location.search)
var reg = /(?:([^&]+)=([^&]+))/g;
while((match = reg.exec(search.substring(1)))!==null){
args[match[1]] = match[2]
}
console.log('args:', args);
第三种方式
就用到了两个String的方法,substring和split
var args = {}
var search = decodeURIComponent(this.props.location.search)
if(search.indexOf('?') != -1){
var text = search.substring(1)
var json = text.split('&')
json.forEach(element => {
args1[element.split('=')[0]] = element.split('=')[1]
});
console.log('args', args)
}
关于以上三种方法,有不足之处请指正,也欢迎大家补充,共同学习。