目录
同源:
跨域:
?跨域请求:?
?JSONP:
JQ中的JSONP:
防抖:
节流:
同源:

?
跨域:

?
?跨域请求:
?JSONP:

?跨域请求报错:
?两个不同域的js:?
??
JQ中的JSONP:



防抖:

?
?防抖实际上就是一种利用settimeout来不断清除定时器和启动定时器的方法。
下面给出一个类似某宝搜索框的下拉内容实现代码:
<button class="btn-get-TBSearch">jsonp get taobao Search</button>
<input type="text" name="searchBar" id="searchBar" placeholder="搜索">
<div class="tpl-List"></div>
<script type="text/html" id="tpl-List">
<ul>
{{each data}}
<li>{{$value}}</li>
{{/each}}
</ul>
</script>
<script>
//jsonp请求淘宝搜索接口
function getSuggestList(userWrite) {
$.ajax({
url: 'http://suggest.taobao.com/sug?q=' + userWrite,
dataType: 'jsonp',
success: res => {
// console.log(res)
getList = res
}
})
}
//防抖
let PRMtimer=null
function preventReqMore(userWrite){
clearTimeout(PRMtimer)
PRMtimer=setTimeout(()=>{
getSuggestList(userWrite)
},2000)
}
let getList = []
let userTypeIn=''
$('#searchBar').on('input propertychange',function () {
userTypeIn=$(this).val()
$('.btn-get-TBSearch').click()
})
$('.btn-get-TBSearch').on('click', e => {
preventReqMore(userTypeIn)
// console.log(getList)
//这里我们的ajax完成方法作用于当前作用域中,不会影响其它ajax
$(document).ajaxComplete(function () {
if (getList !== []) {
// console.log(getList)
let newList=[]
$.each(getList,function (index,item) {
// console.log(item)
$.each(item,function (index1,item1) {
// console.log(item1)
$.each(item1,function (index2,item2) {
if (index2===0){
newList.push(item2)
}
})
})
})
// console.log(newList)
let templateData={
data:newList
}
let getHtml = template('tpl-List', templateData)
$('.tpl-List').html(getHtml)
} else {
console.log('null')
}
})
})
</script>
?其中用到了防抖,jsonp等思想,请耐心领会。
节流:


?
?鼠标跟踪事件优化:
//节流阀
let MouseMoveTimer=null
$(document).on('mousemove',function (e) {
if (MouseMoveTimer===null){
MouseMoveTimer=setTimeout(function () {
$('.yellowPoint').css('top',e.pageY).css('left',e.pageX)
console.log(e.pageX,e.pageY)
MouseMoveTimer=null
},10)
}else return 0
})
?节流和防抖区别:
?
|