jQuery:如何为`$ .ajax启用`beforeSend`({dataType:’jsonp’…`?有什么解决方案吗?

jQuery:如何为$.ajax({dataType:'jsonp'...启用beforeSend $.ajax({dataType:'jsonp'... ?有什么解决方案吗? http://jsfiddle.net/laukstein/2wcpU/

 
$.ajax({ type:"GET", url:'http://lab.laukstein.com/ajax-seo/.json', dataType:'jsonp', async:false, beforeSend:function(data){ // Are not working with dataType:'jsonp' $('#content').html('Loading...'); }, success:function(data){ $('#content').html(data.content); } });

这只是JSONP如何工作的本质,创建一个标记,而不是实际使用XMLHttpRequest来获取数据。 对于你正在做的事情,你可以先运行代码,如下所示:

 $('#content').html('Loading...'); $.ajax({ type:"GET", url:'http://lab.laukstein.com/ajax-seo/.json', dataType:'jsonp', async:false, success:function(data){ $('#content').html(data.content); } }); 

根据jQuery文档

从远程服务器检索数据时(只能使用脚本或jsonp数据类型),使用标记而不是XMLHttpRequest对象执行操作。 在这种情况下,$ .ajax()不返回XMLHttpRequest对象,并且XMLHttpRequest对象和传递给处理函数(如beforeSend)的textStatus参数将是未定义的。 永远不会为JSONP请求触发错误回调。

同样的问题在jQuery论坛上被问到ajax:beforeSend for jsonp requests don't fire

问题的状态是Status : Working on it 。 所以它可能会在未来的版本中出现。

正如Mike Alsups指出的那样

因为语义不一样,我会命名而不是’beforeSend’以外的函数。

还有关系: jsonp is not firing beforeSend?


不能使用beforeSend和jsonp。 期。

你可以使用这段代码:

befor $ .ajax把它,你应该有一个图像(或div,span,…)加载“div_loading”id。

 $("#div_loading").ajaxStart(function(){$(this).show();}); $("#div_loading").ajaxStop(function(){$(this).hide();});