如何添加ajax参数?

时间:2017-04-29 12:30:06

标签: javascript jquery ajax

面对这样一个问题,你无法向ajax请求添加参数,因为有一个“表单数据”,它不能用于添加更多选项。当您在参数'data'中添加另一个变量时,会发生错误。如何做到这一点是在一个请求中发布文件和参数?

原谅错误,错误或不,php文件根本不输出任何内容,而是空值

//Here the file is sent without problems, but the parameters no more don't accept php file, nothing displays in the result
    var fd = new FormData();
    fd.append('file', input[0].files[0]);
    $.ajax({
      url: "/controllers/createNewsController.php",
      data: fd,
      type: "POST",
      processData: false,
      contentType: false,
      success: function(data) {
        $(".news .containers").append(data);
      }
    });

//When this code runs the PHP file won't take anything, although I was expecting the output variables and the file. Using var_dump, $_POST and $_FILES displays array(0){}
var fd = new FormData();
                fd.append('file', input[0].files[0]);
                $.ajax({
                    url: "/controllers/createNewsController.php",
                    data: {fd, title:newsHeader, description:description, hashTag:hashTag, themeHashTag:themeHashTag, viewNews:viewNews},
                    type: "POST",
                    processData: false, 
                    contentType: false,
                    success: function(data){
                        $(".news .containers").append(data);
                    } 
                });

//Similarly, nothing appears in the php file
var fd = new FormData();
                fd.append('file', input[0].files[0]);
                $.ajax({
                    url: "/controllers/createNewsController.php",
                    data: {fd:fd, title:newsHeader, description:description, hashTag:hashTag, themeHashTag:themeHashTag, viewNews:viewNews},
                    type: "POST",
                    processData: false, 
                    contentType: false,
                    success: function(data){
                        $(".news .containers").append(data);
                    } 
                });

1 个答案:

答案 0 :(得分:1)

就像您添加了文件一样,您可以在其中添加更多数据,如:

fd.append('file', input[0].files[0]);

fd.append('var1', val1);
fd.append('var2', val2);