jQuery jsonp用法 CORS

目录结构

.

|-- index.html

|-- lib

|   `-- jquery.js

`-- service

    `-- index.php

 

* index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test jsonp</title>
</head>
<body>
<p>test jsonp</p>
<div id="J_info"></div>
<!-- https://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js -->
<script type="text/javascript" src="./lib/jquery.js"></script>
<script>
  $.ajax({
    type: 'GET',
    url: 'http://localhost:8080/index.php',
    dataType: 'jsonp',
    // 传给后台的get参数名
    jsonp: "callback",
    // 传给后台的get参数值, callback=flightHandler, 后台返回的函数调用函数名
    jsonpCallback:"flightHandler",
  }).done(function(resp) {
      let json = resp.data;
      $("#J_info").html('<p>您查询到航班信息:票价: ' + json.price +
        ' 元,余票: ' + json.tickets + ' 张。</p>');
  }).fail(function(jqXHR, tesxtStatus, errorThrown) {
    console.log("status=" + textStatus);
    if (errorThrown) {
      console.error(errorThrown);
    }
  });

</script>
</body>
</html>

php -S 0.0.0.0:80

* service/index.php

<?php

$cb = $_GET['callback'];

$data = [
    'code' => 0,
    'data' => [
        'price' => 1000,
        'tickets' => 25
    ],
    'message' => 'success'
];
echo sprintf("%s(%s)", $cb, json_encode($data));

cd service

php -S 0.0.0.0:8080

* test:
 

前端发出去的请求 GET

http://localhost:8080/index.php?callback=flightHandler&_=1563623555008

后端响应:

flightHandler({"code":0,"data":{"price":1000,"tickets":25},"message":"success"})

 

如果去掉这2个参数:

jsonp: "callback",   // jsonp默认GET参数名是callback

jsonpCallback:"flightHandler",  // jsonpCallback不指定的情况下, jQuery会自动生成一个jQueryXXXXX这样的函数名

前端发出去的请求:

http://localhost:8080/index.php?callback=jQuery1830050714341655075934_1563624111595&_=1563624111603

后端响应:

jQuery1830050714341655075934_1563624111595({"code":0,"data":{"price":1000,"tickets":25},"message":"success"}) 

 

关键的ajax参数是 dataType: "jsonp" 

dataType指定后端返回值类型

contentType指定前端请求的数据类型

常见的参数值有 application/x-www-form-urlencoded,  application/json

 

jsonp 原理是可以跨域加载js

后端返回js函数调用

https://api.jquery.com/jQuery.ajax/

jsonp

Type: String or Boolean

Override the callback function name in a JSONP request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }. If you don't trust the target of your Ajax requests, consider setting the jsonp property to false for security reasons.

jsonpCallback

Type: String or Function()

Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fareast_mzh

打赏个金币

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值