通过 ajax 发送多个变量

Send multiple variables via ajax

本文关键字:变量 ajax 通过      更新时间:2023-09-26

我在这方面很菜鸟,已经使用 PHP 和 Js 大约 4 个月了,对不起,如果我提出一个菜鸟问题,另外,我是一个讲西班牙语的人,对不起英语语法失败,你要读 =[

基本上,这是我的问题:在这个Php文件中,我有一些Vars和VarArrays,我需要将它们发送到另一个

//First PHP File - This one Search on DataBase, at the end, i have 5 vars, 2 of them are arrays
<?php
$var1 = '1';
$var2 = '2';
$var3 = '3';
$arr1 = array();
$arr2 = array();
//¿How to json_encode the 5 vars above?//
?>

在这个中,我需要捕获以前的值

//Second PHP File
<?php
$newVar1 = $_POST['var1'];
$newVar2 = $_POST['var2'];
$newVar3 = $_POST['var3'];
$newArr1 = $_POST['arr1'];
$newArr2 = $_POST['arr2'];
?>

我想我必须做这样的事情,但我应该怎么做?

$.ajax({
        type: "POST",
        url: "php/FIRSTFILE.php",
        data: ????,
        dataType: "json",
        success:
                function(respuesta)
                {
                  $('#MainDiv').load('php/SECONDFILE.php', function(data) {
                      $(this).html(data);
                  });
                  $('#MainDivLabelVar1').val(respuesta.¿¿EncodeStuff??);
                }
 });

也许你可以像这样对数据进行编码

json_encode(array(
         'var1'   =>    '1',
         'var2'   =>    '2',
         'var3'   =>    '3',
         'arr1'   =>     array(),
         'arr2'   =>     array()
          ));

在这一行中,您将 POST 中的值发送到您的 php 文件:

 data: {id: id, CAT: CAT},

因此,如果您需要接收类似(在文件"second.php中)的数据

<?php
  $newVar1 = $_POST['var1'];
  $newVar2 = $_POST['var2'];
?>

您应该通过以下方式发送:

$.ajax({
        type: "POST",
        url: "php/second.php", 
        data: {var1: 'value1', var2: 'value2'}
});

您可以将 JSON 字符串分解为对象或数组

$js_array = json_encode(array(
         'var1'   =>    '1',
         'var2'   =>    '2',
         'var3'   =>    '3',
         'arr1'   =>     array('a' => 'mobile', 'b' => 'PC'),
         'arr2'   =>     array('price' => 600, 'day' => 7)
          ));
$decode = json_decode($js_array, true); //decode into array
//you could use or seperate something you get back from json decode like this
foreach($decode as $key => $value) {
    if(is_array($value)) {  
        foreach ($value as $k => $v) {
            echo "$k => $v <br />";
        }
    } else {
        echo "$key: $value <br />";     
    }
}

和输出:

var1: 1 
var2: 2 
var3: 3 
a: mobile 
b: PC 
price: 600 
day: 7