jQuery, Convert $.ajax method to $.post

断了今生、忘了曾经 提交于 2019-12-11 05:38:45

问题


i'm trying to make a simple form to upload files with jquery/ajax. this is a part of my code:

  var formData = new FormData($(this)[0]);

  $.ajax({
    url: 'uploader.php',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (data) {
      $('#ShowR').html(data);
    }
  });

i'm trying to change this code to $.post method like this:

var formData = new FormData($(this)[0]);

$.post('uploader.php', {action:"ShowGTR",MyFiles:formData},
function(data) {
 $('#ShowR').html(data);
});

i tried some ways but i couldn't fix the code and in Google Chrome console i got this error:

Uncaught TypeError: Illegal invocation 

so i need your help to fix this code and convert $.ajax method to $.post method. i really appreciate if anyone can help me for this.


回答1:


If the only reason you want to convert your $.ajax call to a $.post call is to add a parameter, then you don't need to convert it ro $.post. What you have to do is append the parameter to the formdata object.

  var formData = new FormData(this);
  formData.append("action", "ShowGTR");

  $.ajax({
    url: 'uploader.php',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (data) {
      $('#ShowR').html(data);
    }
  });



回答2:


$.post( "ajax_file.php", {username:"someone"} ,function( data ) {
    $("#div-id").html(data);
});

This is general syntax of jquery post.



来源:https://stackoverflow.com/questions/23857884/jquery-convert-ajax-method-to-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!