我正在尝试找到无需 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”之前已经声明过并且工作正常。
结果:我在警报中收到“内部服务器错误”。有什么想法吗?
最佳答案
首先 - 向我们展示服务器端发生了什么。
现在关于正在发送的文件:
您应该使用 FormData
元素进行文件提交抛出 Ajax,旧浏览器不支持它,支持此的浏览器是:ie>9、chrome > 7、opera > 12 safari >5 ,android > 3 gecko mobile > 2,opera mobile > 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)
,请尝试查看返回的数据以识别任何其他问题。
关于javascript - 使用 POST 将 Ajax 变量发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20126163/