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 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题