将带有POST的Ajax变量发送到PHP

Send Ajax Variables with POST to PHP

本文关键字:PHP 变量 Ajax POST      更新时间:2023-09-26

我正在努力寻找在没有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);
        }
    });

注意:变量"位置"以前已经声明过,工作正常。

结果:我在警报中得到"内部服务器错误"。有什么想法吗?

首先,向我们展示服务器端的情况。

现在关于正在发送的文件:

您应该为文件提交使用FormData元素抛出Ajax,旧浏览器不支持它,支持它的浏览器有:ie>9,chrome>7,opera>12safari>5,android>3gecko-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),请尝试查看返回的数据以确定任何其他问题。