原生方式须要定义一个回调函数,用来接收和处理数据。获取数据的地址包含这个回调函数名。新建一个<script>标签,地址赋值给标签的src。javascript
<script> function callbackFunction(result, methodName) { console.log(result); } function getJsonpData() { let script = document.createElement('script'); script.type="text/javascript"; script.src='https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction'; document.head.appendChild(script); } </script>
jQuery方式须先引入jQuery文件。
代码中不用定义回调函数名,获取数据的地址把回调函数名改成"?"。
方式有两个:php
<script> $.ajax({ url: 'https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?', type: 'GET', dataType: 'JSONP', }) .done(function(data) { console.log(data); }) .fail(function(error) { console.log(error); }) .always(function() { console.log("complete"); }); </script>
<script> $.getJSON('https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?', function(data) { console.log(data); }) </script>