Ajax POST到PHP var并返回 [英] Ajax POST to PHP var and return

查看:51
本文介绍了Ajax POST到PHP var并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Web应用程序,我想将该复选框的值传递给PHP变量而不提交.因此,我正在使用Ajax传递值.

I'm developing a web app where I want to pass the checkbox value to a PHP variable without submitting. Therefore I'm using Ajax to pass the value.

代码页1:

<div class="sliderWrapper">
     input type="checkbox" name="val1" id="val1" value="Value 1">
 </div>
 <div class="sliderWrapper">
     input type="checkbox" name="val2" id="val2" value="Value 2">
 </div>

 <p id="test"></p>

<script>
 $("input[type=checkbox]").on("change", function () {
        var ids = [];
        $('input[type=checkbox]:checked').each(function () {
            ids.push($(this).val());
        });
        $.ajax({
            url: "page2.php",
            type: "POST",
            async: true,
            cache: false,
            data: ({value: ids, semester}),
            dataType: "text",
            success: function (data) {
                //alert(data)
                $("p#test").html(data);
            }
        });
    });
 </script>

代码页2:

if(isset($_POST['value'])) {
    $values = $_POST['value'];

    foreach($values as $value){
        echo $value;
    }
}

所以我将值传递回HTML

标签,我想将其作为PHP变量在第1页上使用.这可能吗?

So I'm passing the value back to an HTML

tag and I want to use it back on page 1 as a PHP variable. Is this possible?

推荐答案

否.

查看事件的顺序:

  1. 第1页PHP在服务器上运行
  2. 服务器将结果发送到浏览器
  3. 浏览器加载页面并运行Ajax
  4. 浏览器发出Ajax请求
  5. 浏览器得到响应

您不能在第1页中将响应用作PHP变量,因为:

You can't use the response as a PHP variable in page 1 because:

  • PHP变量存在于服务器上,数据现在位于浏览器中
  • 第1步后,PHP脚本完成,因此程序不再运行,并且没有地方放置变量

如果要对服务器上的数据进行处理,请在第2页上进行.(您可以将函数放在其他PHP文件中,如果需要,可以在两个页面上 include 在它们之间共享逻辑).

If you want to do something with the data on the server, then do it in page 2. (You can put a function in a different PHP file and include it on both pages if you want to share logic between them).

如果您要更改显示在浏览器中的内容,请执行以下操作:

If you want to change what is displayed in the browser in response to that then:

  • 第2页返回确定应显示的内容所需的信息
  • 编写JavaScript来读取数据并对DOM进行所需的更改

这篇关于Ajax POST到PHP var并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆