[英]Send Ajax Variables with POST to PHP
我正在嘗試找到沒有GET方法將變量從Javascript發送到PHP的最佳方法。 我找到了一種使用AJAX通過POST方法發送的方法:
<form method="POST" id="post" enctype="multipart/form-data">
<input type="file" name="image_upload[]" id="img1" />
<input type="file" name="image_upload[]" id="img2" />
<input type="file" name="image_upload[]" id="img3" />
<input type="text" name="description" id="description" />
<textarea class="intext" name="editor" id="editor"></textarea>
<input type="text" name="state" id="state" disabled="true" />
<input type="text" name="city" id="city" disabled="true" />
<input type="submit" id="submit" />
</form>
我正在嘗試使用jQuery提交表單:
$('#post').submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "cpage.php",
data: {
'variable1': 'content var1',
'variable2': 'content var2'
},
success: function () {
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
注意:變量“ position ”已在之前聲明,並且可以正常工作。
結果:我在警報中收到“ Internal Server Error ”。 有任何想法嗎?
首先-向我們展示服務器端的情況。
現在關於要發送的文件:
您應該使用FormData
元素將文件提交給Ajax,舊瀏覽器不支持它,支持該瀏覽器的瀏覽器是:ie> 9,chrome> 7,Opera> 12 safari> 5,android> 3 gecko mobile> 2,Opera手機> 12。
使用這樣的東西:
$('#post').submit(function (event) {
event.preventDefault();
if( window.FormData !== undefined ) //make sure that we can use FormData
{
var formData = new FormData($('form#post'));
$.ajax({
type: "POST",
url: "cpage.php",
data: formData ,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data); // <- for debugging
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
} else {
//fallback
}
});
如您所見,我添加了console.log(data)
,請嘗試查看返回的數據以確定其他問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.