使用ajax将多个变量保存为字符串

时间:2014-09-25 21:24:05

标签: javascript php ajax

我有一组变量,我使用ajax发送到php文件。而不是将它们全部作为单个变量发送,有没有办法将它们作为1个字符串发送,然后在php页面中分解该字符串?

主页。

<script type="text/javascript">
        $(document).ready(function(argument) {
            $('#save').click(function(){
                // Get edit field value
                $edit1a = $('#edit1a').html();
                $edit2a = $('#edit2a').html();
                $edit3a = $('#edit3a').html();
                $edit4a = $('#edit4a').html();
                $edit5a = $('#edit5a').html();
                $edit6a = $('#edit6a').html();
                $edit7a = $('#edit7a').html();
                $edit8a = $('#edit8a').html();
                $edit9a = $('#edit9a').html();
                $edit10a = $('#edit10a').html();
                $edit11a = $('#edit11a').html();
                $.ajax({
                    url: 'get.php',
                    type: 'post',
                    data: {edit1: $edit1a, edit2: $edit2a, edit3: $edit3a, edit4: $edit4a, edit5: $edit5a, edit6: $edit6a, edit7: $edit7a, edit8: $edit8a, edit9: $edit9a, edit10: $edit10a, edit11: $edit11a,},
                    datatype: 'html',
                    success: function(rsp){
                            alert(rsp);
                        }
                });
            });
        });
    </script>

php页面。

$edit1 = @$_POST['edit1'];
$edit2 = @$_POST['edit2'];
$edit3 = @$_POST['edit3'];
$edit4 = @$_POST['edit4'];
$edit5 = @$_POST['edit5'];
$edit6 = @$_POST['edit6'];
$edit7 = @$_POST['edit7'];
$edit8 = @$_POST['edit8'];
$edit9 = @$_POST['edit9'];
$edit10 = @$_POST['edit10'];
$edit11 = @$_POST['edit11'];



$insert =mysql_query('INSERT INTO pages (edit1, edit2, 
edit3, edit4, edit5, edit6, edit7,edit8, edit9, edit10, 
edit11)   VALUES("'.$edit1.','.$edit2.','.$edit3.','.$edit4.','.$edit5.','.$edit6.',
'.$edit7.','.$edit8.','.$    edit9.','.$edit10.','.$edit11.'")')
or die ("could not insert new Data:" .mysql_error()); 

1 个答案:

答案 0 :(得分:0)

您可以这样做:

            $edit1a = $('#edit1a').html();
            $edit2a = $('#edit2a').html();
            var sepStr = '<SEPARATOR>'; //reserve whatever character or string you want
            var combined1a2a = $edit1a + sepStr + $edit2a;
            $.ajax({
                url: 'get.php',
                type: 'post',
                data: {combined: combined1a2a},
                datatype: 'html',
                success: function(rsp){
                        alert(rsp);
                    }
            });

在PHP中:

$values = explode('<SEPARATOR>', POST['combined']);
//access like $values[0], $values[1], etc.

(如果我是你的话,我会停止在javascript var名称前面使用$。你会开始弄清楚什么是javascript以及那是什么PHP。)