for循环执行两次,但数据只保存一次php ajax

时间:2017-12-19 09:03:35

标签: javascript php ajax for-loop

  <html>
 <head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 </head>
 <body onload="searchVideo();">

<script>
 var data_length =  2;
 for(var i=0; i<data_length; i++){
console.log(i);
 var pageToken = '';
  var numOfResult = 0;
 var maxResults = 200;
 function searchVideo(){
   var separator = ',';
    $.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken=' + pageToken + '&playlistId=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-&key=Apikey&callback=?',function(data){

    var l = data.items.length;
    pageToken = data.nextPageToken;
    numOfResult += l;
    var itemUrl = '';
      var videoids = [];
         for(var j = 0; j < l; j++) {
          if( j == 0) {
            separator = ',';
          }
          else {
            separator = ',';
          }

            var videoid = data.items[j].snippet.resourceId.videoId;
            var title = data.items[j].snippet.title;
           $.ajax({
                method: 'POST',
               url:    'add.php',
               data: { title: title, videoid: videoid }
                 })
              .done(function(data) {
                });
        }

        if( numOfResult < maxResults) {
          searchVideo();

        }

         });
       }
   }
  </script>
</body>
 </html>

add.php

<?php
 ini_set('max_execution_time', 300);
include 'config.php';
 $title = mysqli_real_escape_string($mysql,$_POST['title']);
 $videoid = mysqli_real_escape_string($mysql,$_POST['videoid']);
 $thumbnail_url = 'http://img.youtube.com/vi/'.$videoid.'/hqdefault.jpg';
 $sql = "INSERT INTO ytfb(name,video_name,thumbnail_url)    VALUES('$title','$videoid','$thumbnail_url')";
$create_post_query=mysqli_query($mysql,$sql);
     if(!$create_post_query)
    {
   die("Connection failed".mysqli_error($mysql));
     }?>

从上面的代码数据只保存一次。数据未保存两次,但运行for循环两次以保存数据两次。所以任何人都可以帮助我如何使用ajax保存数据两次。只保存一次数据,数据不会保存两次,因为我给出了长度2意味着2个循环它应该保存两次

4 个答案:

答案 0 :(得分:1)

根据我的评论你的for循环执行一次不执行2次。如果你想执行2次j<=1

这一行的问题。我已修复问题

for(var j = 0; j <= 1; j++) {

我在本地解决了问题..你的函数searchVideo没有执行两次。 onload函数只在第一次调用。我上传了一些代码示例。你应该放弃这个样本

示例代码。删除函数并编写没有函数的代码

  <html>
 <head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 </head>
 <body>

<script>
 var data_length =  2;
 for(var i=0; i<2; i++){
    alert(i);
console.log(i);
 var pageToken = '';
  var numOfResult = 0;
 var maxResults = 200;


            var videoid = "asdf";
            var title = "erwe";
           $.ajax({
                method: 'POST',
               url:    'test4.php',
               data: { title: title, videoid: videoid }
                 })
              .done(function(data) {
                });


       }

  </script>
</body>
 </html>

test4.php

<?php
echo "string";
?>

实现功能的其他方式

 <html>
 <head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 </head>
 <body>

<script>
 var data_length =  2;
 for(var i=0; i<2; i++){
    searchVideo();
    alert(i)
console.log(i);
 var pageToken = '';
  var numOfResult = 0;
 var maxResults = 200;
 function searchVideo(){

            var videoid = "asdf";
            var title = "erwe";
           $.ajax({
                method: 'POST',
               url:    'test4.php',
               data: { title: title, videoid: videoid }
                 })
              .done(function(data) {
                });
        }

       }

  </script>
</body>
 </html>

答案 1 :(得分:0)

我们只调用了一次搜索视频功能。(在页面加载时) 从body标签中删除onload函数 请尝试此代码

if( numOfResult < maxResults) {
          searchVideo();

        }

但我不知道searchVideo函数中的以下条件

<?php
    $link = mssql_connect('192.168.1.17', 'root', '123456');

    if (!$link)
        die('Unable to connect!');
    if (!mssql_select_db('user', $link))
        die('Unable to select database!');

    $result = mssql_query('SELECT * FROM dbo.user');
    print_r($result);
    ?>

答案 2 :(得分:0)

试试这个

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var pageToken ='';
var data_length =  2;
var numOfResult = 0;
var maxResults = 200;
var i=1;
function searchVideo() {
    var separator = ',';
    $.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken='+pageToken+'&playlistId=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-&key= xxxx',function(data){
        console.log(data)
        var l = data.items.length;
        pageToken = data.nextPageToken;
        numOfResult += l;
        var itemUrl = '';
        var videoids = [];
        for(var j = 0; j < l; j++) {
            if( j == 0) {
                separator = ',';
            } else {
                separator = ',';
            }
            var videoid = data.items[j].snippet.resourceId.videoId;
            var title = data.items[j].snippet.title;
           console.log("called");
            $.ajax({
               method: 'POST',
               url:    'add.php',
               data: { title: title, videoid: videoid }
           }).done(function(data) {
           });
        }

        if( numOfResult < maxResults) {
          searchVideo();

        }
        if( numOfResult == maxResults && i<data_length) {
            i++;
          pageToken = ''; 
   numOfResult = 0;
   maxResults = 200;
          searchVideo();

        }

    });
}
searchVideo()
</script>

答案 3 :(得分:0)

试试这个

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var paylistIdArray=['PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-','PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-'];
var pageToken ='';
var data_length =  paylistIdArray.length;
var numOfResult = 0;
var maxResults = 200;
var i=0;
var paylistId=paylistIdArray[0];
function searchVideo() {
    var separator = ',';
    $.getJSON('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&pageToken='+pageToken+'&playlistId='+paylistId+'&key= xxxx',function(data){
        console.log(data)
        var l = data.items.length;
        pageToken = data.nextPageToken;
        numOfResult += l;
        var itemUrl = '';
        var videoids = [];
        for(var j = 0; j < l; j++) {
            if( j == 0) {
                separator = ',';
            } else {
                separator = ',';
            }
            var videoid = data.items[j].snippet.resourceId.videoId;
            var title = data.items[j].snippet.title;
           console.log("called");
            $.ajax({
               method: 'POST',
               url:    'add.php',
               data: { title: title, videoid: videoid }
           }).done(function(data) {
           });
        }

        if( numOfResult < maxResults) {
          searchVideo();

        }
        if( numOfResult == maxResults && i<data_length) {
            i++;
            pageToken = ''; 
            numOfResult = 0;
            maxResults = 200;
            paylistId=paylistIdArray[i];
            searchVideo();
        }

    });
}
searchVideo()
</script>