开发者

jQuery: How to enable `beforeSend` for `$.ajax({dataType:'jsonp'...`? Is there any solution?

开发者 https://www.devze.com 2023-02-03 13:21 出处:网络
jQuery: How to enable beforeSend for $.ajax({dataType:\'jsonp\'...? Is there any solution? http://jsfiddle.net/laukstein/2wcpU/

jQuery: How to enable beforeSend for $.ajax({dataType:'jsonp'...? Is there any solution? http://jsfiddle.net/laukstein/2wcpU/

<div id="content"></div>
<script>
$.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:funct开发者_StackOverflow中文版ion(data){
        $('#content').html(data.content);
    }
});
</script>


This is just the nature of how JSONP works, creating a <script> tag, not actually using a XMLHttpRequest to get data. For what you're doing, you can just run the code before, like this:

$('#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);
  }
});


As per jQuery documentation

When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the operation is performed using a tag rather than an XMLHttpRequest object. In this case, no XMLHttpRequest object is returned from $.ajax(), and the XMLHttpRequest object and the textStatus arguments passed to the handler functions such as beforeSend will be undefined. The error callback will never be fired for JSONP requests.

The same question is asked at the jQuery forums ajax:beforeSend for jsonp requests don't fire

The question's status is Status : Working on it. So it might be there at a future release.

And as Mike Alsups noted

I would name than function something other than 'beforeSend' since the semantics are not the same.

Also related : jsonp is not firing beforeSend?


Cannot use beforeSend with jsonp. Period.


you can use this code:

befor $.ajax put it, and you should have an image(or div,span ,...) loading with "div_loading" id.

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

精彩评论

暂无评论...
验证码 换一张
取 消