JSONP:是否需要回调? [英] JSONP: Is a callback necessary?

查看:164
本文介绍了JSONP:是否需要回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AJAX,jQuery和Phonegap创建一个iOS/Droid应用程序.后端是一个Drupal 7网站,它通过Web服务提供内容.不过,对于JSONP回调的必要性,我有些困惑.

我的理解是,JSONP是必需的,以便允许跨域请求.并且,部分地,它通过将JSON数据包装在回调函数中而起作用,从而使其成为对象.

但是,我发现我可以在没有回调的情况下发送JSONP请求,并在没有回调函数的情况下通过jQuery解析数据.因此,JSONP数据看起来与JSON数据完全一样.

我错过了什么吗?如果将数据作为函数提供是JSONP的优势之一,那么在流程的某个阶段是否不要求提供它?我是否通过不发送回调参数来绕过某种程度的安全性?

谢谢!

仅供参考,这是jQuery AJAX代码:

$.ajax({
    type: 'GET',
    cache: false,
    url: 'http://www.example.com/mobile/menu/devel-gosto.jsonp',
    dataType: 'jsonp',
    timeout: menuLoadTimeout,
    success: function (data) {
        menu = populateSlider(data.tree, 0);
    }
}); 

因此,我将dataType设置为'jsonp',调用了返回JSONP数据的Web服务,但未在URL中提供回调. Web服务响应时没有回调包装.而且一切正常.

解决方案

没有回调,JSONP调用将无法工作.数据被加载到script标记中,如果代码不是以方法调用的形式出现,则结果将只是被丢弃的对象,并且将永远不会调用success回调方法.

ajax方法正在向URL添加回调参数,即使您未指定回调参数.

在文档中,dataType设置的"jsonp"值下:

在URL的末尾添加一个额外的"?callback =?,以指定 回调."

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

I'm creating an iOS / Droid app using AJAX, jQuery, and Phonegap. The backend is a Drupal 7 site serving content via web services. I'm a little confused about the necessity for a JSONP callback, though.

My understanding is that JSONP is required in order to allow cross domain requests. And, in part, it works by wrapping the JSON data within a callback function, thus making it an object.

However, what I'm finding is that I can send the JSONP request without a callback, and parse the data via jQuery without the callback function. So the JSONP data looks exactly like JSON data.

Am I missing something? If providing the data as function is one of the benefits of JSONP, shouldn't it be required at some stage in the process? Am I bypassing some level of security by not sending a callback parameter?

Thanks!

FYI, here is the jQuery AJAX code:

$.ajax({
    type: 'GET',
    cache: false,
    url: 'http://www.example.com/mobile/menu/devel-gosto.jsonp',
    dataType: 'jsonp',
    timeout: menuLoadTimeout,
    success: function (data) {
        menu = populateSlider(data.tree, 0);
    }
}); 

So I'm setting the dataType to 'jsonp', calling to a web service that returns JSONP data, but leaving the callback out of the URL. The web service responds without a callback wrapper. And everything works fine.

解决方案

A JSONP call doesn't work without a callback. The data is loaded in a script tag, and if the code is not in a form of a method call, the result would just be an object that was discarded, and the success callback method would never be called.

The ajax method is adding a callback parameter to the URL even if you don't specify one.

In the documentation, under the "jsonp" value for the dataType setting:

"Adds an extra "?callback=?" to the end of your URL to specify the callback."

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

这篇关于JSONP:是否需要回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆