美文网首页
jsonp应用

jsonp应用

作者: 南崽 | 来源:发表于2020-03-19 23:00 被阅读0次

1. 服务端 JSONP 格式数据

服务端文件 jsonp.php 代码为:

jsonp.php 文件代码
<?php
header('Content-type: application/json');
//获取回调函数名
$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
//json数据
$json_data = '["customername1","customername2"]';
//输出jsonp格式的数据
echo $jsoncallback . "(" . $json_data . ")";
?>

2. 客户端实现 callbackFunction 函数

<script type="text/javascript">
function callbackFunction(result, methodName)
{
    var html = '<ul>';
    for(var i = 0; i < result.length; i++)
    {
        html += '<li>' + result[i] + '</li>';
    }
    html += '</ul>';
    document.getElementById('divCustomers').innerHTML = html;
}
</script>

页面展示

<div id="divCustomers"></div>

客户端页面完整代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSONP 实例</title>
</head>
<body>
<div id="divCustomers"></div>
<script type="text/javascript">
function callbackFunction(result, methodName)
{
    var html = '<ul>';
    for(var i = 0; i < result.length; i++)
    {
        html += '<li>' + result[i] + '</li>';
    }
    html += '</ul>';
    document.getElementById('divCustomers').innerHTML = html;
}
</script>
<script type="text/javascript" src="https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>

jQuery 使用 JSONP

  • 以上代码可以使用 jQuery 代码实例:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JSONP 实例</title>
    <script src="https://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js"></script>    
</head>
<body>
<div id="divCustomers"></div>
<script>
$.getJSON("https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?", function(data) {
    
    var html = '<ul>';
    for(var i = 0; i < data.length; i++)
    {
        html += '<li>' + data[i] + '</li>';
    }
    html += '</ul>';
    
    $('#divCustomers').html(html); 
});
</script>
</body>
</html>

相关文章

  • jsonp应用

    vue中通过created调用_getRecommend方法 getRecommend是通过jsonp(url, ...

  • jsonp应用

    1. 服务端 JSONP 格式数据 如客户想访问 : https://www.runoob.com/try/aja...

  • JSONP全面分析

    JSONP JSONP是JSON with padding(填充式JSON或参数式JSON)的简写,是应用JSON...

  • 2018-06-27

    JSONP 应用 服务端JSONP格式数据 假设客户期望返回JSON数据:["customername1","cu...

  • JSONP、JQuery发送AJAX、JSONP请求

    1.JSONP 2.JQuery发送AJAX、JSONP请求 1.JSONP JSONP利用JavaScript...

  • JS-18day

    1、jsonp公开接口 2、jQuery-jsonp 3、jsonp

  • 2018-12-10

    节点操作 ajax jsonp jQuery-jsonp jsonp公开接口

  • jsonp原理

    模拟jsonp原理 servlet 测试 http://localhost/jq/jsonp.jsp JSONP ...

  • 2018-07-30

    一 ajax 二 jsonp 三 jquery-jsonp 四 jsonp公开接口

  • ajax

    1、ajax 2、jsonp 3、jQuery-jsonp 4、jsonp公开接口

网友评论

      本文标题:jsonp应用

      本文链接:https://www.haomeiwen.com/subject/dagryhtx.html