Ajax / JS将变量传递给PHP并将其保存在成功[复制]

时间:2022-06-25 00:02:01

This question already has an answer here:

这个问题在这里已有答案:

The title of this question is probably misleading, I didn't know a good way to consicely ask what I need help with.

这个问题的标题可能会产生误导,我不知道一个好的方式来提出我需要帮助的问题。

So basically, I use the following ajax to send a javacript variable on index.php to a separate php file (page2.php)

基本上,我使用以下ajax将index.php上的javacript变量发送到单独的php文件(page2.php)

var Variable1 = '1';
$.ajax({
        type: "POST",
        url: 'page2.php',
        data: "NewVariable=" + Variable1,
        success: function() {
              ...Save or echo the value of $newervariable here ....
        }
});

So basically above I am sending the variable Variabl1 to page2.php . Page2.php looks something like this:

所以基本上我将变量Variabl1发送到page2.php。 Page2.php看起来像这样:

<?php
     if(isset($_POST['NewVariable'])) {
          $NewVariable = $_POST['NewVariable'];
          $NewerVariable = $NewVariable + 1;
}

?>

I know the example is kind of obsolete because you could just do add 1 using javascript without having the 2nd php page, but I just simplified it down really it boils down to me needing the 2nd php page, and also knowing how to save the values of it after success (if it's even possible)

我知道这个例子已经过时,因为你可以在没有第二个php页面的情况下使用javascript添加1,但我只是简化了它真的归结为我需要第二个php页面,并且还知道如何保存值成功之后(如果可能的话)

2 个解决方案

#1


0  

On JS

success: function(data) {
          Variable1=data;
        }

On PHP:

<?php
     if(isset($_POST['NewVariable'])) {
          $NewVariable = $_POST['NewVariable'];
          $NewerVariable = $NewVariable + 1;
          echo $NewerVariable;
}

#2


0  

In php page echo the output :

在php页面中回显输出:

<?php
 if(isset($_POST['NewVariable'])) {
    $NewVariable = $_POST['NewVariable'];
    $NewerVariable = $NewVariable + 1;
    echo $NewerVariable; 
}
?>

And in your js :

在你的js:

var Variable1 = '1';
$.ajax({
    type: "POST",
    url: 'page2.php',
    data: "NewVariable=" + Variable1,
    success: function( data ) {
       // data --> data you echo from server side
         alert( data );
       // do whatever you want here
    }
});

#1


0  

On JS

success: function(data) {
          Variable1=data;
        }

On PHP:

<?php
     if(isset($_POST['NewVariable'])) {
          $NewVariable = $_POST['NewVariable'];
          $NewerVariable = $NewVariable + 1;
          echo $NewerVariable;
}

#2


0  

In php page echo the output :

在php页面中回显输出:

<?php
 if(isset($_POST['NewVariable'])) {
    $NewVariable = $_POST['NewVariable'];
    $NewerVariable = $NewVariable + 1;
    echo $NewerVariable; 
}
?>

And in your js :

在你的js:

var Variable1 = '1';
$.ajax({
    type: "POST",
    url: 'page2.php',
    data: "NewVariable=" + Variable1,
    success: function( data ) {
       // data --> data you echo from server side
         alert( data );
       // do whatever you want here
    }
});