javascript - 本地调用淘宝api跨域解决
世界只因有你
世界只因有你 2017-05-19 10:17:45
[JavaScript讨论组]

今天在/q/10...上看到第一个答案上淘宝有个手机号的api,于是在本地写了个html文件发ajax请求到这个api.但是提示跨域报错.没处理过这种问题,该怎么解决呢?麻烦贴上代码哦~小白在此非常感谢~

世界只因有你
世界只因有你

全部回复(3)
phpcn_u1582

JSONP。。

迷茫

可以通关JSONP方式进行跨域

<script>
$(document).ready(function(){ 
    $("#search").click(function(){ 
        $.ajax({ 
            type: "GET",     
            url: "http://127.0.0.1:8000/ajaxdemo/serverjsonp.php?number=" + $("#keyword").val(),
            dataType: "jsonp",
            jsonp: "callback",
            success: function(data) {
                if (data.success) {
                    $("#searchResult").html(data.msg);
                } else {
                    $("#searchResult").html("出现错误:" + data.msg);
                }  
            },
            error: function(jqXHR){     
               alert("发生错误:" + jqXHR.status);  
            },     
        });
    });
    
    $("#save").click(function(){ 
        $.ajax({ 
            type: "POST",     
            url: "http://127.0.0.1:8000/ajaxdemo/serverjsonp.php",
            data: {
                name: $("#staffName").val(), 
                number: $("#staffNumber").val(), 
                sex: $("#staffSex").val(), 
                job: $("#staffJob").val()
            },
            dataType: "json",
            success: function(data){
                if (data.success) { 
                    $("#createResult").html(data.msg);
                } else {
                    $("#createResult").html("出现错误:" + data.msg);
                }  
            },
            error: function(jqXHR){     
               alert("发生错误:" + jqXHR.status);  
            },     
        });
    });
});
</script>

这是之前写的应用jsonp跨域的测试文件,你可以参考

PHPz
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>test</title>
</head>

<body>
    <input type="text" id="tel">
    <input type="button" id="btn" value="submit">
    <script src="https://lib.sinaapp.com/js/jquery/3.1.0/jquery-3.1.0.min.js"></script>
    <script>
    $('#btn').click(function() {
        var tel = $('#tel').val().trim();
        if (!tel) {
            return;
        }
        $.ajax({
                url: 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm',
                dataType: 'jsonp',
                data: {
                    tel: tel
                },
            })
            .done(function(rs) {
                console.log(rs);
            })
            .fail(function() {
                console.log("error");
            })
            .always(function() {
                console.log("complete");
            });

    });
    </script>
</body>

</html>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号