2017-08-16 138 views
0

我收到一个控制台错误消息:$ .each(...)。done在运行此代码时不是函数。将数据插入到数据库中的php代码正在工作,因为我可以在数据库中看到文件名。我只需要修复我的循环来停止出现错误,但不知道这里有什么问题。如何在ajax调用中使用.each

$("#edit_pic").on("click", function (e) { 
     e.preventDefault(); 
     var files = $('input[name="file"]').val() 
     var data = JSON.parse(files) 
    } 

    $.each(data, function (index, item) { 

     $.ajax({ 
      url: 'functions/add-support-images.php', 
      type: 'POST', 
      dataType: 'json', 
      data: { 
       data: item.file_name 
      }, 
      beforeSend: function() { 
       $("#edit_pic").prop("disabled", true).html("Uploading..."); 
      }, 
     }); 
    }) 

    .done(function (data) { 
     if (!data.success) { 
      console.log(data.message); 


     } else { 

      console.log(data.message); 

     } 

    }) 

PHP:

$response = array(); 
      $id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT); 
      $stmt = $link->prepare("INSERT INTO `product_images` (`pic_name`,`product_id`) VALUES (?, ?)"); 
      $stmt->bind_param("si", $_POST['data'], $id); 
      $stmt->execute(); 
      $stmt->close(); 


     $response['success'] = true; 
     $response['message'] = "success"; 
+0

'每个'没有一个完成的方法,但阿贾克斯功能呢。你可能希望访问jquery文档。 – scrappedcola

回答

1

尝试移动.done$.ajax后:

$("#edit_pic").on("click", function (e) { 
    e.preventDefault(); 
    var files = $('input[name="file"]').val() 
    var data = JSON.parse(files) 
} 

$.each(data, function (index, item) { 

    $.ajax({ 
     url: 'functions/add-support-images.php', 
     type: 'POST', 
     dataType: 'json', 
     data: { 
      data: item.file_name 
     }, 
     beforeSend: function() { 
      $("#edit_pic").prop("disabled", true).html("Uploading..."); 
     }, 
    }).done(function (data) { 
     if (!data.success) { 
      console.log(data.message); 


     } else { 

      console.log(data.message); 

     } 

    }); 
}); 

编辑

正如在评论中提到,与上面的代码,你会看到成功mes因为它们是单独发送的,因此每个项目都需要圣人。要在一个 Ajax调用发送的所有项目,你可以做这样的事情:

let items = []; 

$.each(data, function (index, item) { 
    items.push({data: item.file_name}); 
}); 

$.ajax({ 
    url: 'functions/add-support-images.php', 
    type: 'POST', 
    dataType: 'json', 
    data: items, 
    beforeSend: function() { 
     $("#edit_pic").prop("disabled", true).html("Uploading..."); 
    }, 
}).done(function (data) { 
    if (!data.success) { 
     console.log(data.message); 
    } else { 
     console.log(data.message); 
    } 
}); 

注:这可能需要更新你的PHP代码接受项目的数组插入,而不是单个项目。

+0

谢谢。该错误不再显示。但是,我的成功消息显示出与插入记录相同的次数。 – user8463989

+0

是的,那是因为你正在为每条记录做一个Ajax调用。另一种方法是更新您的PHP代码以接受要更新的值的数组。然后你可以使用'$ .each'将每个'item.file_name'的值放入一个数组中。然后进行'$ .each'外部的ajax调用*。 –

+0

你在那里失去了我。我已经添加了PHP到我原来的问题。 – user8463989