如何理解jQuery的ajax方法的参数:jsonp和jsonpCallback(我并没有问什么是jsonp)?

我并不是想问什么是jsonp,我想知道的仅仅是jQuery提供的ajax方法中,jsonp这个参数的意义~

阅读 5.4k
3 个回答

摘自 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.

emmmmm……感觉问的有点广——建议配合百度食用
简单来说的话、jsonp是属于一种跨域的数据获取方式。
原理本质上利用了<script>引用可跨域的形式。把连接当成一个js或者css之类的引用,丢进script再通过返回值来读取。
而jsonpCallback是指你自己回调方法的方法名。因为jsonp需要服务器端做配合。比如你访问了一个接口。他返回的内容实际是一串js代码比如:

do("xxxxxxxx")

而这个do就是你的jsonpCallback。你需要自己另外再写一个function do($str);在里面对数据进行解析。

其实后来其实大部分都由服务器直接可以解决跨域问题了所以感觉jsonp就很少见了……

jsonp是dataType的一个类型JSONP 格式
早期因WEB安全原因,Ajax默认情况下是不能进行跨域请求的 所以jsonp的意义就是简洁说就是改变json数据的格式可以跨域 原理 可以具体自己去看

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进