JavaScript发送错误的get请求

时间:2019-05-20 18:30:50

标签: javascript html

所以基本上,我有一个图片上传页面,用户可以上传图片。我使用laravel作为后端,此后一直没有工作,并且服务器一直返回错误,因此我将发布请求更改为GET,我发现而不是脚本sendind之类的http://localhost:8000/upload?title='whatever'&body='theimageselected.jpg' 当然,titlebody的值是变量。根据用户的要求,它们会有所不同。 它发送此:

  

http://localhost:8000/upload?[object%20Object]&_=1558376643031

为什么?

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" type="image/x-icon" href="https://static.codepen.io/assets/favicon/favicon-aec34940fbc1a6e787974dcd360f2c6b63348d4b1f4e06c77743096d55480f33.ico" />
<link rel="mask-icon" type="" href="https://static.codepen.io/assets/favicon/logo-pin-8f3771b1072e3c38bd662872f6b673a722f4b3ca2421637d5596661b4e2132cc.svg" color="#111" />
<title>CodePen - Image Upload With Live Preview using FormData</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<style>
      .container {
  padding-top: 3%;
}

.hide-element {
  display: none;
}

.glyphicon-remove-circle {
  float: right;
  font-size: 2em;
  cursor: pointer;
}


/*
* http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/
*/

.btn-file {
  position: relative;
  overflow: hidden;
  /*box-shadow: 10px 10px 5px #888888;*/
}

.btn-file input[type=file] {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 100%;
  min-height: 100%;
  font-size: 100px;
  text-align: right;
  filter: alpha(opacity=0);
  opacity: 0;
  outline: none;
  background: white;
  cursor: inherit;
  display: block;
}

.alert,
.well {
  box-shadow: 10px 10px 5px;
  -moz-box-shadow: 10px 10px 5px;
  -webkit-box-shadow: 10px 10px 5px;
}

#uploadDataInfo p {
  margin-left: 2%;
  margin-top: 3%;
  font-size: 1.2em;
}

.media-left #edit {
  z-index: 1000;
  cursor: pointer;
}

.thumbnail #edit {
  position: absolute;
  display: inline;
  z-index: 1000;
  top: 1px;
  right: 15px;
  cursor: pointer;
}

.thumbnail #delete {
  position: absolute;
  display: inline;
  z-index: 1000;
  margin-top: 4%;
  top: 20px;
  right: 15px;
  cursor: pointer;
}

.caption input[type="text"] {
  /*width: 80%;*/
}

.thumbnail .fa-check-circle {
  color: #006dcc;
  *color: #0044cc;
}

.thumbnail .fa-times-circle {
  color: #E74C3C;
}

.modal-header .close {
  float: right !important;
  margin-right: -30px !important;
  margin-top: -25px !important;
  background-color: white !important;
  border-radius: 15px !important;
  width: 30px !important;
  height: 30px !important;
  opacity: 1 !important;
}

.modal-header {
  padding: 0px;
  min-height: 0px;
}

.modal-dialog {
  top: 50px;
}

.media-left img {
  cursor: pointer;
}

.label-tags {
  font-size: 16px;
  padding: 1%;
  color: black;
  background-color: white;
  border: 1px solid blue;
  border-radius: 4px;
  margin: 3px;
}

.label-tags i {
  cursor: pointer;
}
    </style>
<script>
  window.console = window.console || function(t) {};
</script>
<script>
  if (document.location.search.match(/type=embed/gi)) {
    window.parent.postMessage("resize", "*");
  }
</script>
</head>
<body translate="no">

<div id="individualImagePreview" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">

<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><i class="fa fa-times"></i></button>
</div>
<div class="modal-body">
<img src="" alt="default image" class="img-responsive" id="individualPreview" />
</div>
<div class="modal-footer" id="displayTags">
<div class="pull-left">
</div>
</div>
</div>
</div>
</div>

<div id="progressModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">

<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<div id="ajaxLoad">
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuemax="100" id="progressIndicator" style="">
<span class="sr-only">45% Complete</span>
</div>
</div>
<i class="fa fa-cog fa-spin fa-4x"></i> </div>
</div>
<div class="modal-footer hide-element">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="container">
<div class="alert hide-element" role="alert" id="errorMessaage"></div>
<div class="alert hide-element" role="alert" id="file-error-message">
<span class='glyphicon glyphicon-remove-circle'></span>
<p></p>
</div>
<form class="well" id="imagesUploadForm">
<label for="file">Select files to upload</label>
<br />

<span class="btn btn-primary btn-file">
Browse <input type="file" multiple="multiple" accept="image/*" id="uploadImages" /></span>
<p class="help-block">
Only jpg,jpeg,png file with maximum size of 2 MB is allowed.
</p>

<button type="button" data-toggle="modal" data-target="#myModal" class="btn btn-lg btn-primary disabled" value="Preview" name="imagesUpload" id="imagesUpload">Preview</button>
</form>
<div id="uploadDataInfo" class="alert hide-element">
<a href="#" class="close" data-dismiss="alert" aria-label="close">
<i class="fa fa-times"></i>
</a>
<p class="" id="toManyFilesUploaded"></p>
<p class="" id="filesCount"></p>
<p class="" id="filesSupported"></p>
<p class="" id="filesUnsupported"></p>
</div>
<div class="hide-element" id="previewImages">
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="0" title="" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label><input type="text" class="form-control" value="" name="description" /></p>
<p><label for="caption">Caption: </label><input type="text" class="form-control" value="" name="caption" /></p>
<p><label for="tags">Tags:max of 3 tags.comma seperated </label><input type="text" class="form-control" value="" name="tags" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo0">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete0">Delete</a>
</div>
</div>
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="1" title="" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label><input type="text" class="form-control" value="" name="description" /></p>
<p><label for="caption">Caption: </label><input type="text" class="form-control" value="" name="caption" /></p>
<p><label for="tags">Tags: </label><input type="text" class="form-control" value="" name="tags" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo1">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete1">Delete</a>
</div>
</div>
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="2" title="" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label><input type="text" class="form-control" value="" name="description" /></p>
<p><label for="caption">Caption: </label><input type="text" class="form-control" value="" name="caption" /></p>
<p><label for="tags">Tags: </label><input type="text" class="form-control" value="" name="tags" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo2">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete2">Delete</a>
</div>
</div>
<div class="media">
<div class="media-left">
<img class="media-object thumbnail" src="img/200x200.gif" alt="" id="3" data-toggle="modal" data-target="#individualImagePreview" />
</div>
<div class="media-body">
<p><label for="description">Description: </label>
<input type="text" class="form-control" name="description" value="" /></p>
<p><label for="caption">Caption: </label>
<input type="text" class="form-control" name="caption" value="" /></p>
<p><label for="tags">Tags: </label>
<input type="text" class="form-control" name="tags" value="" /></p>
<a role="button" class="btn btn-primary hide-element" id="undo3">Undo</a>
<a role="button" class="btn btn-danger pull-right" id="delete3">Delete</a>
</div>
</div>
<button class="btn btn-primary pull-left" id="sendImagesToServer" data-toggle="modal" data-target="#progressModal" data-keyboard="false" data-backdrop="static">Update &amp; Preview</button>
</div>
<br /><br />


<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">

<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><i class="fa fa-times"></i></button>
</div>
<div class="modal-body">
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner" role="listbox" id="previewItems">
</div>

<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<div class="modal-footer hide-element">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://static.codepen.io/assets/common/stopExecutionOnTimeout-de7e2ef6bfefd24b79a3f68b414b87b8db5b08439cac3f1012092b2290c719cd.js"></script>
<script id="rendered-js">
      $(document).ready(function () {
  $('[data-toggle="tooltip"]').tooltip({
    html: true });

  $('.media').addClass('hide-element');
  $('#imagesUploadForm').submit(function (evt) {
    evt.preventDefault();
  });
  $('#edit').click(function () {
    console.log('click detected inside circl-o of edit');
    $('#edit').toggleClass('fa-circle-o').toggleClass('fa-check-circle');
    if ($('#edit').hasClass('fa-check-circle')) {
      $('#captionForImage').toggleClass('hide-element');
    } else {
      $('#captionForImage').toggleClass('hide-element');
    }
  });
  $('#delete').click(function () {
    console.log('click detected inside circl-o of delete');
    $('#delete').toggleClass('fa-circle-o').toggleClass('fa-times-circle');
  });
  //namespace variable to determine whether to continue or not
  var proceed = true;
  //Ensure that FILE API is supported by the browser to proceed

  if (proceed) {
    var input = "";
    var formData = new FormData();
    $('input[type=file]').on("change", function (e) {
      var counter = 0;
      var modalPreviewItems = "";
      input = this.files;
      $($(this)[0].files).each(function (i, file) {
        formData.append("file[]", file);
      });
      $('#previewImages').removeClass('hide-element');
      $('#imagesUpload').removeClass('disabled');
      var successUpload = 0;
      var failedUpload = 0;
      var extraFiles = 2;
      var size = input.length;
      $(input).each(function () {
        var reader = new FileReader();
        var uploadImage = this;
        console.log(this);
        reader.readAsArrayBuffer(this);
        reader.onload = function (e) {
          var magicNumbers = validateImage.magicNumbersForExtension(e);
          var fileSize = validateImage.isUploadedFileSizeValid(uploadImage);
          var extension = validateImage.uploadFileExtension(uploadImage);
          var isValidImage = validateImage.validateExtensionToMagicNumbers(magicNumbers);
          var thumbnail = validateImage.generateThumbnail(uploadImage);
          if (fileSize && isValidImage) {
            $('#' + counter).parents('.media').removeClass('hide-element');
            $('#' + counter).attr('src', thumbnail).height('200');
            $('#uploadDataInfo').removeClass('hide-element').addClass('alert-success');
            successUpload++;
            modalPreviewItems += carouselInsideModal.createItemsForSlider(thumbnail, counter);

          } else {
            $('#uploadDataInfo').removeClass('hide-element alert-success').addClass('alert-warning');
            failedUpload++;
          }
          counter++;
          if (counter === size) {
            $('#myCarousel').append(carouselInsideModal.createIndicators(successUpload, "myCarousel"));
            $('#previewItems').append(modalPreviewItems);
            $('#previewItems .item').first().addClass('active');
            $('#carouselIndicators > li').first().addClass('active');
            $('#myCarousel').carousel({
              interval: 2000,
              cycle: true });

            if (size > 4) {
              $('#toManyFilesUploaded').html("Only files displayed below will be uploaded");
              extraFiles = size - 4;
            }

            $('#filesCount').html(successUpload + " files are ready to upload");
            if (failedUpload !== 0 || extraFiles !== 0) {
              failedUpload === 0 ? "" : failedUpload;
              extraFiles === 0 ? "" : extraFiles;
              $('#filesUnsupported').html(failedUpload + extraFiles + " files were not selected for upload");
            }

          }
        };
      });

    });
    $(document).on('click', '.glyphicon-remove-circle', function () {
      $('#file-error-message').addClass('hide-element');
    });
    $("body").on("click", ".media-object", function () {
      var image = $(this).attr('src');
      $("#individualPreview").attr('src', image);
      var tags = [];
      var displayTagsWithFormat = "";
      $(this).parents('.media').find('input[type="text"]').each(function () {
        if ($(this).attr('name') === 'tags') {
          tags = $(this).val().split(",");
          $.each(tags, function (index) {
            displayTagsWithFormat += "<span class = 'label-tags label'>#" + tags[index] + "  <i class='fa fa-times'></i></span>";
          });
          $("#displayTags").html("<div class='pull-left'>" + displayTagsWithFormat + "</div>");
          //console.log(tags);
        }
      });
    });
    var toBeDeleted = [];
    var eachImageValues = [];
    $('.media').each(function (index) {
      var imagePresent = "";
      $("body").on("click", "#delete" + index, function () {
        imagePresent = $("#" + index).attr('src');
        $("#undo" + index).removeClass('hide-element');
        $("#" + index).attr('src', './img/200x200.gif');
        $("#delete" + index).addClass('hide-element');
        toBeDeleted.push(index);
        //console.log(toBeDeleted);                      
        $("#delete" + index).parent().find('input[type="text"]').each(function () {
          var attribute = $(this).attr('name');
          var attributeValue = $(this).val();
          eachImageValues[attribute + index] = attributeValue;
          //console.log(eachImageValues);

        });
        //console.log(toBeDeleted.length);
        if (toBeDeleted.length === 4) {
          $('#sendImagesToServer').prop('disabled', true).html('No Files to Upload');

        } else {
          $('#sendImagesToServer').prop('disabled', false).html('Update &amp; Preview');
        }

        $("#delete" + index).parent().find('input[type="text"]').prop('disabled', true).addClass('disabled');
      });
      $("body").on("click", "#undo" + index, function () {
        $("#" + index).attr('src', imagePresent);
        $("#undo" + index).addClass('hide-element');
        $("#delete" + index).removeClass('hide-element');
        var indexToDelete = toBeDeleted.indexOf(index);
        if (indexToDelete > -1) {
          toBeDeleted.splice(indexToDelete, 1);
          // console.log(toBeDeleted);
          $("#delete" + index).parent().find('input[type="text"]').prop('disabled', false).removeClass('disabled');
        }
        if (toBeDeleted.length === 4) {
          $('#sendImagesToServer').prop('disabled', true).html('No Files to Upload');

        } else {
          $('#sendImagesToServer').prop('disabled', false).html('Update &amp; Preview');
        }
      });
    });
    $('body').on("click", "#sendImagesToServer", function () {

      var counter = 0;
      var imageData = "";
      var consolidatedData = [];
      $('.media').each(function () {
        var description = "";
        var caption = "";
        var tags = "";
        $('.media').find('input[type="text"]').each(function (index) {
          if ((index === 0 || index <= 11) && counter <= 11) {
            counter++;
            var attributeName = "";
            var attributeValue = "";

            attributeName = $(this).attr('name');
            attributeValue = $(this).val();
            switch (attributeName) {
              case "title":
                title = attributeName;
                // console.log(description);
                break;
              case "caption":
                body = attributeName;
                // console.log(caption);
                break;
              case "tags":
                tags =attributeName;
                // console.log(tags);
                break;
              default:
                break;}

            if (counter % 3 === 0) {
              imageData = new imageInformation(description, caption, tags);
              consolidatedData.push(imageData);
              //JSON.stringify(consolidatedData);                        
              //console.log(toBeDeleted);
            }
          }
        });
      });
      imageData = new deleteList(toBeDeleted);
      consolidatedData.push(imageData);
      var sendData = JSON.stringify(consolidatedData);
      formData.append("important", sendData);
      $.ajax({
        type: 'GET',
        url: '/upload',
        xhr: function () {
          var customXhr = $.ajaxSettings.xhr();
          if (customXhr.upload) {
            customXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
          }
          return customXhr;
        },
        data: {title:"test",body:"body"},
        dataType: 'json',
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
          $('#ajaxLoad').addClass('hide-element');
          $('#successResponse').html(data.message);
          console.log(data.message + " inside success function");
        },
        error: function (data) {
          $('#successResponse').html(data.responseJSON.message).addClass('label label-danger').css({
            'font-size': '18px' });

          console.log(data.responseJSON.message + " inside error function");
        } });


      function progressHandlingFunction(e) {
        if (e.lengthComputable) {
          $('#progressIndicator').css({
            'width': e.loaded });

        }
      };
      //
      //console.log(JSON.stringify(consolidatedData));
    });

    function imageInformation(description, caption, tags) {
      this.description = description;
      this.title = caption;
      this.tags = tags;
      this.type = "image";

    };

    function deleteList(toBeDeleted) {
      this.toBeDeleted = toBeDeleted;
    };
    var validateImage = {
      magicNumbersForExtension: function (event) {
        var headerArray = new Uint8Array(event.target.result).subarray(0, 4);
        var magicNumber = "";
        for (var counter = 0; counter < headerArray.length; counter++) {if (window.CP.shouldStopExecution(0)) break;
          magicNumber += headerArray[counter].toString(16);
        }window.CP.exitedLoop(0);
        return magicNumber;
      },
      isUploadedFileSizeValid: function (fileUploaded) {
        var fileSize = fileUploaded.size;
        var maximumSize = 2097125;
        var isValid = "";
        if (fileSize <= maximumSize) {
          isValid = true;
        } else {
          isValid = false;
        }
        return isValid;
      },
      uploadFileExtension: function (fileUploaded) {
        var fileExtension = "";
        var imageType = "";
        imageType = fileUploaded.type.toLowerCase();
        fileExtension = imageType.substr(imageType.lastIndexOf('/') + 1);
        return fileExtension;
      },
      validateExtensionToMagicNumbers: function (magicNumbers) {
        var properExtension = "";
        if (magicNumbers.toLowerCase() === "ffd8ffe0" || magicNumbers.toLowerCase() === "ffd8ffe1" ||
        magicNumbers.toLowerCase() === "ffd8ffe8" ||
        magicNumbers.toLocaleLowerCase() === "89504e47") {
          properExtension = true;

        } else {
          properExtension = false;
        }
        return properExtension;
      },
      generateThumbnail: function (uploadImage) {
        if (window.URL)
        imageSrc = window.URL.createObjectURL(uploadImage);else

        imageSrc = window.webkitURL.createObjectURL(uploadImage);
        return imageSrc;
      } };

    var carouselInsideModal = {
      createIndicators: function (carouselLength, dataTarget) {
        var carouselIndicators = '<ol class = "carousel-indicators" id="carouselIndicators">';
        for (var counter = 0; counter < carouselLength; counter++) {if (window.CP.shouldStopExecution(1)) break;
          carouselIndicators += '<li data-target = "#' + dataTarget + '"data-slide-to="' + counter + '"></li>';
        }window.CP.exitedLoop(1);
        carouselIndicators += "</ol>";
        return carouselIndicators;
      },
      createItemsForSlider: function (imgSrc, counter) {
        var item = '<div class = "item">' + '<img src="' + imgSrc + '" id="preview' + counter + '" /></div>';
        return item;
      } };

  }
});
      //# sourceURL=pen.js
    </script>








    <script>

    $('.laravel-like').on('click', function(){
  if($(this).hasClass('disabled'))
    return false;

  var item_id = $(this).data('item-id');
  var vote = $(this).data('vote');

  $.ajax({
       method: "post",
       url: "/",
       data: {item_id: item_id, vote: vote},
       dataType: "json"
    })
    .done(function(msg){
      if(msg.flag == 1){
        if(msg.vote == 1){
          $('#'+item_id+'-like').removeClass('outline');
          $('#'+item_id+'-dislike').addClass('outline');
        }
        else if(msg.vote == -1){
          $('#'+item_id+'-dislike').removeClass('outline');
          $('#'+item_id+'-like').addClass('outline');
        }
        else if(msg.vote == 0){
          $('#'+item_id+'-like').addClass('outline');
          $('#'+item_id+'-dislike').addClass('outline');
        }
      $('#'+item_id+'-total-like').text(msg.totalLike == null ? 0 : msg.totalLike);
      $('#'+item_id+'-total-dislike').text(msg.totalDislike == null ? 0 : msg.totalDislike);
      }
    })
    .fail(function(msg){
      alert(msg);
    });
});


$(document).on('click', '.reply-button', function(){
  if($(this).hasClass("disabled"))
      return false;
  var toggle = $(this).data('toggle');
  $("#"+toggle).fadeToggle('normal');
});

$(document).on('submit', '.laravelComment-form', function(){
    var thisForm = $(this);
    var parent = $(this).data('parent');
    var item_id = $(this).data('item');
    var comment = $('textarea#'+parent+'-textarea').val();

    $.ajax({
         method: "get",
         url: "/laravellikecomment/comment/add",
         data: {parent: parent, comment: comment, item_id: item_id},
         dataType: "json"
      })
      .done(function(msg){
        $(thisForm).toggle('normal');
        var newComment = '<div class="comment" id="comment-'+msg.id+'" style="display: initial;"><a class="avatar"><img src="'+msg.userPic+'"></a><div class="content"><a class="author">'+msg.userName+'</a><div class="metadata"><span class="date">Today at 5:42PM</span></div><div class="text">'+msg.comment+'</div><div class="actions"><a class="reply reply-button" data-toggle="'+msg.id+'-reply-form">Reply</a></div><form class="ui laravelComment-form form" id="'+msg.id+'-reply-form" data-parent="'+msg.id+'" data-item="'+item_id+'" style="display: none;"><div class="field"><textarea id="'+msg.id+'-textarea" rows="2"></textarea></div><input type="submit" class="ui basic small submit button" value="Reply"></form></div><div class="ui threaded comments" id="'+item_id+'-comment-'+msg.id+'"></div></div>';
        $('#'+item_id+'-comment-'+parent).prepend(newComment);
        $('textarea#'+parent+'-textarea').val('');
      })
      .fail(function(msg){
        alert(msg);
      });

    return false;
});


$(document).on('click', '#showComment', function(){
    var show = $(this).data("show-comment");
    $('.show-'+$(this).data("item-id")+'-'+show).fadeIn('normal');
    $(this).data("show-comment", show+1);
    $(this).text("Show more");
});


$(document).on('click', '#write-comment', function(){
    $($(this).data("form")).show();
});


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

1 个答案:

答案 0 :(得分:1)

您可以尝试

"spec": {
    "ports": [
      {
        "name": "prometheus",
        "protocol": "TCP",
        "port": 80,
        "targetPort": 24231