其他分享
首页 > 其他分享> > Ajax跨域代码封装

Ajax跨域代码封装

作者:互联网

taobao_sug.html

<!DOCTYPE html>
<html lang="en">
<!-- 淘宝提示词案例 -->

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="myutils.js"></script>
<title>Document</title>
<style>
    li {
        list-style-type: none;
    }
</style>
</head>
<script>
    window.onload = function() {
        var btn = document.querySelector("#btn");
        btn.onclick = function() {
            var keyword = document.querySelector("#keyword").value;
            // console.log(keyword);

            myAjax({
                url: "https://suggest.taobao.com/sug",
                data: {
                    q: keyword
                },
                success: function(data) {
                    var liTag = "";
                    for (var i = 0; i < data.result.length; i++) {
                        var temp = data.result[i];
                        var tempTag = temp[0];
                        liTag += "<li>" + tempTag + "<li>";
                    }
                    var ulTag = document.querySelector("ul");
                    ulTag.innerHTML = liTag;
                },
                jsonp: "callback",
                jsonpCallback: "haha"
            });

        };
    };
</script>

<body>

    <input type="text" id="keyword" placeholder="请输入相关的关键字">
    <input type="button" id="btn" value="查询">

    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>

</body>

</html

myutils.js

//跨域代码封装
function myAjax(obj) {
    var defaults = {
        type: "get",
        url: "#",
        data: {},
        success: function(data) {},
        jsonp: "callback",
        jsonpCallback: "hehe"
    };

    //传过来的对象覆盖默认对象值
    for (var key in obj) {
        defaults[key] = obj[key];
    }

    var params = "";
    for (var attr in defaults.data) {
        params += attr + "=" + defaults.data[attr] + "&";
    }

    if (params) {
        //去除最后一个&
        params = params.substring(0, params.length - 1);
        defaults.url += "?" + params;
    }
    defaults.url += "&" + defaults.jsonp + "=" + defaults.jsonpCallback;
    console.log(defaults.url);

    //动态创建script
    var script = document.createElement("script");
    script.src = defaults.url;

    window[defaults.jsonpCallback] = function(data) {
        defaults.success(data);
    }

    var head = document.querySelector("head");
    head.appendChild(script);
}

运行结果:
在这里插入图片描述
如何想要运行此代码,先实现在本机模拟访问域名服务器,具体操作可以看我之前写的博客进行操作

https://blog.csdn.net/qq_48701993/article/details/122640527

标签:function,封装,跨域,url,Ajax,params,defaults,var,data
来源: https://blog.csdn.net/qq_48701993/article/details/122639893