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 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决