dsz7121 2013-10-26 08:09
浏览 277

ajax发送POST两次,从PHP接收双重/重复结果

i found out my JS sends POST method twice to my PHP file, thats why i keep getting double/repetitive results from my PHP.

enter image description here

This JS event, upon .keyup() will execute an ajax.

    $(document).ready(function() {  
    var getUrl = $('#url');
    var youtube = regex here
    var web = regex here    

        getUrl.keyup(function() {

        if  (youtube.test(getUrl.val())) {
        var youtube_url = getUrl.val().match(youtube)[0];
        $.ajax ({
                type:"POST",
            url:"getyoutube.php",
            data: {youtube_url:youtube_url},
            success: function(html) { $('.echotest').append(html); }
        }); }

    else if (web.test(getUrl.val())) {
        var extracted_url = getUrl.val().match(web)[0];                 
                    $.post("curl_fetch.php?url="+ extracted_url, {
                }, function(response){
           $('#loader').html($(response).fadeIn('slow'));
           $('#cur_image').val(1);
        });} 
    }); 
}); 

the data will be received by getyoutube.php and should only print json result of a particular youtube video once.

 //some code ommitted
 $youtube ="https://gdata.youtube.com/feeds/api/videos/'.$matches[0].'?v=2&alt=jsonc";
 $curl = curl_init($youtube);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 $return = curl_exec($curl);
 curl_close($curl);
 $test = json_decode($return, true);
 print_r($test);

i cant seem to figure out why my AJAX post keeps sending POSTS method twice

  • 写回答

3条回答

  • drd43058 2013-10-26 08:44
    关注

    Couple of things to try:

    1) Make sure you bind and unbind your key up event

    2) Use a global variable to make sure only one ajax request gets sent at once

    i.e.:

    var ajaxrequest = false; //GLOBAL
    
    function getyoutubedata(){
    
      if(ajaxrequest != false){
         return;  
      }
    
      ajaxrequest = $.ajax ({
            type:"POST",
            url:"./includes/getyoutube.php",
            data: {youtube_url:youtube_url},
            success: function(html) { $('.echotest').append(html); ajaxrequest = false; }
      });
    
    }
    

    Btw thing to note the youtube api supports jsonp callbacks so you might want to consider doing this through that

    3) Try to check if the content of the input field has changed even before calling the above function

    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记