關於使用JSONP跨域請求數據的三種方式

原生方式

原生方式須要定義一個回調函數,用來接收和處理數據。獲取數據的地址包含這個回調函數名。新建一個<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方式須先引入jQuery文件。
代碼中不用定義回調函數名,獲取數據的地址把回調函數名改成"?"。
方式有兩個:php

$.ajax請求
<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>
$.getJSON請求。
<script>
  $.getJSON('https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?', function(data) {
    console.log(data);
  })
</script>
相關文章
相關標籤/搜索