2016-12-14 31 views
0

上的ajax發佈數據和文件。如何在此處使用事件onclick

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

現在我想通過使用後()函數將它張貼

Java的腳本:

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

但沒有序列號文件

+0

你的問題是什麼LEM?請在你的問題中定義實際問題並更新它。 –

+0

實際的問題是文件未序列化。 –

+0

你的意思是表單數據沒有被序列化? –

回答

0

我的建議是:儘量分開有html和定義「的」 jQuery的功能的「attacheventlistener」功能或事件回調JS(這樣比較容易)。

你的問題是,當你需要傳遞一個有效的url時,你傳遞的是字符串「url」,所以直接在ajax url字段上寫入url或者在你的form標籤上定義一個數據屬性。 data-url =「http:// whatever」,並從事件中捕獲此值。

如果你使用jquery的「on」函數極其簡單,你可以通過jquery的「data」函數通過「this」var獲得它的數據值。

喜歡的東西...

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

,不過也許你並不需要的網址是一個變種。

0

如果我理解正確,問題是什麼都沒有發佈。 問題是是,你正試圖通過AJAX做一個文件上傳,這是沒有錯的,但它需要做的事情在這裏不同的顯示:
jQuery Ajax File Upload

0

首先,我需要說的是,如果你想上傳文件,我的意思是如果您的表單有文件輸入,然後根據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."); 
     } 
    }); 
} 

我認爲這應該是工作的罰款。

UPDATE: 如果你想發佈文本數據,那麼你應該使用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."); 
     } 
    }); 
} 
+0

我想發佈兩個文本字段數據和文件, With without Reload –

+1

@AponAhmed查看更新。 –

+0

我有很多文本字段超過30個。 –

0

,得到形式像

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

屬性這應該工作

0

您可以通過表單數據添加額外的數據

使用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'); 
    }); 
相關問題