繁体   English   中英

如何在onclick事件上使用Ajax发布数据和文件

[英]How can i post data and file by using ajax on event onclick

HTML在这里。

 <form id="myForm"> <input type="text" name="name"> <input type="file" name="userImage"> <button onclick="post('./example.php')" type="button">Save</button> </form> 

现在我想使用post()函数发布它

Java脚本:

 Function post(url){ $.ajax({ url:url, type: 'POST', data: $("#myform").serialize(), success: function (data) { alert("successfully posted."); } }); } 

但未序列化文件

我的建议是:尝试分开在“ attacheventlistener”功能或“ on” jquery的功能上定义事件回调的html和js(这样更容易)。

您的问题是,当您需要传递有效的URL时传递字符串“ url”,因此直接将URL写在ajax url字段上或在表单标签上定义数据属性,例如data-url =“ http:// whatever ”,并从事件中捕获此值。

如果您使用jquery的“ on”函数极其简单,则可以通过jquery的“ data”函数在“ this”变量上获取它的数据值。

就像是 ...

$("#myForm").on("click", 
      function() {
            post(this.data("url"));
});

但可能您不需要将url设为var。

如果我理解正确,那么问题是什么都没有发布。 事实是您正在尝试通过ajax上传文件,这没有错,但是需要按以下所示进行不同的操作:
jQuery Ajax文件上传

首先,我要说的是,如果您要上传文件,则意味着您的表单具有文件输入,然后根据RFC-7578添加表单属性enctype="multipart/form-data" 您还可以查看http://www.w3schools.com/tags/att_form_enctype.asp的用法。

然后再次移至html部分。 假设您有一个表单输入,例如

<form action="some_domain/example.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="fileId"/>
    <input type="text" name="firstName" id="name">
    <button onclick="post('some_domain/example.php')" type="button">Save</button>
</form>

现在使用ajax发布文件数据:

function post(url){
   $.ajax({
        url:url,
        type: 'POST',
        processData:false,
        contentType:false,
        data: $('#fileId')[0].files[0],
        success: function (data) {
           alert("successfully posted.");
        }
    });
}

我认为这应该很好。

更新:如果您也想发布文本数据,则应该使用FormData对象。

function post(url){
var formData = new FormData();
   var files = document.getElementById("fileId").files;
   for (var i = 0; i < files.length; i++) {
       var file = files[i];
       formData.append('files[]', file, file.name);
}
formData.append('firstName',$('#name').val());
$.ajax({
        url:url,
        type: 'POST',
        processData:false,
        contentType:false,
        data: formData,
        success: function (data) {
           alert("successfully posted.");
        }
    });
}

给表单一个像这样的属性

<form  enctype="multipart/form-data" ....>

这应该工作

您可以在表单数据中添加额外的数据

使用serializeArray并添加其他数据:

var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
    success: function(data) {
         //var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
        // do what ever you want with the server response
    },
    error: function() {
        alert('error handing here');
   });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM